第一种方法:
list = [1, 2, 3, 4]
list1 = []
for i in list:
for j in list:
if i == j:
continue
for k in list:
if (i == k) or (j == k):
continue
aa = 100*i+10*j+k
list1.append(aa)
print(list1)
print(len(list1))
输出结果为:
[123, 124, 132, 134, 142, 143, 213, 214, 231, 234, 241, 243, 312, 314, 321, 324, 341, 342, 412, 413, 421, 423, 431, 432]
24
第二种方法:
list = []
for i in range(1, 5):
for j in range(1, 5):
for k in range(1, 5):
if (i != j) and (j != k) and (i != k):
a = int("%s%s%s" % (i, j, k))
list.append(a)
print(list)
print(len(list))
输出结果为:
[123, 124, 132, 134, 142, 143, 213, 214, 231, 234, 241, 243, 312, 314, 321, 324, 341, 342, 412, 413, 421, 423, 431, 432]
24
第3种方法:用集合去除重复元素
import pprint
list_num = ['1','2','3','4']
list_result = []
for i in list_num:
for j in list_num:
for k in list_num:
if len(set(i + j + k)) == 3:
list_result += [int(i + j + k)]
print("能组成%d个互不相同且无重复数字的三位数:"%len(list_result))
pprint.pprint(list_result)
输出结果为:
能组成24个互不相同且无重复数字的三位数:
[123,
124,
132,
134,
142,
143,
213,
214,
231,
234,
241,
243,
312,
314,
321,
324,
341,
342,
412,
413,
421,
423,
431,
432]