Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/sorting/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python是否按相同顺序排序2个不同大小的列表?_Python_Sorting - Fatal编程技术网

Python是否按相同顺序排序2个不同大小的列表?

Python是否按相同顺序排序2个不同大小的列表?,python,sorting,Python,Sorting,我想根据元素顺序对2个不同的长度列表进行排序 我有两个python列表,它们共享一些元素,如: list_1 = [b,e,a,d,c] list_2 = [b,a,c,k,l,f,d] 我知道使用itertools的zip_最长,我可以对2个不同大小的列表进行排序: for k,j in zip_longest(list_1 ,list_2 ,fillvalue=None): print (k,j) 这段代码告诉我: b b e a a c d k c l None f None

我想根据元素顺序对2个不同的长度列表进行排序

我有两个python列表,它们共享一些元素,如:

list_1 = [b,e,a,d,c]
list_2 = [b,a,c,k,l,f,d]
我知道使用itertools的zip_最长,我可以对2个不同大小的列表进行排序:

for k,j in zip_longest(list_1 ,list_2 ,fillvalue=None):
     print (k,j)
这段代码告诉我:

b b
e a
a c
d k
c l
None f
None d
但是,是否也可以按相同的顺序对相同的值进行排序,如:

[a,b,c,d,e,None,None,None]
[a,b,c,d,None,f,k,l]
或类似的格式:

a,a
b,b
c,c
d,d
e,None
None,f
None,k
None,l
非常感谢

您可以使用一个集合来获取两个列表中的所有元素,然后将列表中缺少的值替换为无:

list_1 = ['b','e','a','d','c']
list_2 = ['b','a','c','k','l','f','d']
combined = sorted(set(list_1 + list_2))

new_list_1 = [c if c in list_1 else None for c in combined]
new_list_2 = [c if c in list_2 else None for c in combined]

print(new_list_1, new_list_2, sep='\n')
结果:

['a', 'b', 'c', 'd', 'e', None, None, None]
['a', 'b', 'c', 'd', None, 'f', 'k', 'l']
您可以使用集合获取两个列表中的所有元素,然后将列表中缺少的值替换为无:

list_1 = ['b','e','a','d','c']
list_2 = ['b','a','c','k','l','f','d']
combined = sorted(set(list_1 + list_2))

new_list_1 = [c if c in list_1 else None for c in combined]
new_list_2 = [c if c in list_2 else None for c in combined]

print(new_list_1, new_list_2, sep='\n')
结果:

['a', 'b', 'c', 'd', 'e', None, None, None]
['a', 'b', 'c', 'd', None, 'f', 'k', 'l']

为什么输出中“d”和“f”之间没有?请使用函数示例代码。你的列表元素不是字符串。@奥斯汀,我想是因为“e”在“f”之前,在“d”之后alphabetically@Austin因为没有对应于e的元素。非常感谢您的评论。@Jab我只是想用Abstraction解释一下。我只需要理解解决方案背后的算法或想法,但你是对的,下次我会小心的,为什么输出中“d”和“f”之间没有?请使用函数示例代码。你的列表元素不是字符串。@奥斯汀,我想是因为“e”在“f”之前,在“d”之后alphabetically@Austin因为没有对应于e的元素。非常感谢您的评论。@Jab我只是想用Abstraction解释一下。我只需要理解解决方案背后的算法或想法,但你是对的,下次我会小心的