按字典顺序打印列表(包含整数)的列表

时间:2018-08-30 17:42:56

标签: python lexicographic

任务:为您提供三个整数x,y和z以及一个整数n。您必须打印所有可能的坐标的列表,其中的总和不等于n。打印按字典顺序升序打印列表。 下面是我的代码。除了按字典顺序打印外,其他都可以正常工作。下面是我的代码。是否有更好的方法来获取包含整数的列表的字典顺序?

from itertools import combinations
lst=[]
if __name__ == '__main__':
    x = int(input())
    y = int(input())
    z = int(input())
    n = int(input())
    lst=[[a,b,c]  for b in range(y+1) for c in range(z+1)   for a in range(x+1) ]

finallst=[]
for items in combinations(lst,3):
    for nums in items:
       x=sum(nums)
       if x!=n and nums not in finallst:
            finallst.append(nums)

f_finallst= (sorted(map(str,(finallst)))) #converted to string to get lexicographic order
print (f_finallst) 
My result=['[0, 0, 0]', '[0, 0, 1]', '[0, 1, 0]', '[1, 0, 0]', '[1, 1, 1]']
Expected result=[[0, 0, 0], [0, 0, 1], [0, 1, 0], [1, 0, 0], [1, 1, 1]]

4 个答案:

答案 0 :(得分:0)

print([coords 
       for coords in itertools.product(range(x+1), range(y+1), range(z+1))
       if sum(coords) != n])

答案 1 :(得分:0)

通过使用map(str, finallst),可以将列表中的每个元素强制转换为str。您想保留元素的原样,但使用str作为排序键。

f_finallst= sorted(finallst, key=str)

答案 2 :(得分:0)

x = int(input())
y = int(input())
z = int(input())
n = int(input())
lists=[[i,j,k] for i in range(x+1)
               for j in range(y+1)
               for k in range(z+1) if (i+j+k)!=n]
print(lists)

答案 3 :(得分:0)

我发现,添加lambda函数(基本上用作排序比较的关键)可以解决问题。有关详细说明,请阅读here

if __name__ == '__main__':
x = int(input())
y = int(input())
z = int(input())
n = int(input())

orginal_list = [[i, j, k] for k in range(z+1) for j in range(y+1) for i in range(x+1) if i + j + k != n]

sorted_list = sorted(orginal_list, key = lambda i: (len(i), i)) 


print(sorted_list)
相关问题