我在对列表理解创建的单个元组进行排序时遇到问题。 假设我们有:
words = [(a, b, c) for a in al for b in bl for c in cl]
现在我想通过以下方式对每个元组 (a, b, c) 进行排序:
map(lambda x: sorted(x), words)
这给了我错误:“元组”对象不可调用。
我也试过:
for i in range(len(words)):
out = [words[i][0], words[i][1], words[i][2]]
print out.sort()
它打印了一堆 Nones。
我错过了什么? 提前致谢。
最佳答案
您可以将元组作为创建的一部分进行排序:
words = [sorted((a, b, c)) for a in al for b in bl for c in cl]
请注意,这将为您提供一个列表列表,而不是元组列表,因为 sorted
返回一个列表。如果你真的想要元组,你必须这样做
words = [tuple(sorted((a, b, c))) for a in al for b in bl for c in cl]
关于python - 排序由python中的列表理解生成的元组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29531437/