我正在尝试使用Python 3来使用list_one对list_two进行排序并输出到list_sorted。如果缺少字段的值,那么我希望看到一个空值。输出与list_one
具有相同数量的项目list_one = ['one', 'two', 'three', 'four', 'five', 'six', 'seven']
list_two = ['seven', 'five', 'four', 'three', 'one']
list_sorted = []
for i in list_one:
for field in list_two:
if i == field:
list_sorted.append(field)
else:
list_sorted.append(None)
print ('final output:', list_sorted)
所需的输出是:
['one', None, 'three', 'four', 'five', None, 'seven']
但它实际上正在输出:
[None, None, None, None, 'one', None, None, None, None, None, None, None, None, 'three', None, None, None, 'four', None, None, None, 'five', None, None, None, None, None, None, None, None, 'seven', None, None, None, None]
我目前的想法是答案涉及enumerate,但我不确定。任何帮助都将非常赞赏。
答案 0 :(得分:1)
将list_two
转换为集合,然后根据该元素是否在list_two
中构建列表解析。
set_two = set(list_two)
list_sorted = [x if x in set_two else None for x in list_one]
print(list_sorted)
['one', None, 'three', 'four', 'five', None, 'seven']
答案 1 :(得分:1)
您并没有真正排序任何内容,但看起来您可以实现您想要的只是测试i
中是否存在list_two
。删除内部for
循环。
list_one = ['one', 'two', 'three', 'four', 'five', 'six', 'seven']
list_two = ['seven', 'five', 'four', 'three', 'one']
list_sorted = []
for i in list_one:
if i in list_two:
list_sorted.append(i)
else:
list_sorted.append(None)
print ('final output:', list_sorted)