def common_elements(list1, list2):
"""
Return a list containing the elements which are in both list1 and list2
>>> common_elements([1,2,3,4,5,6], [3,5,7,9])
[3, 5]
>>> common_elements(['this','this','n','that'],['this','not','that','that'])
['this', 'that']
"""
for element in list1:
if element in list2:
return list(element)
Run Code Online (Sandbox Code Playgroud)
到目前为止,但似乎无法让它工作!
有任何想法吗?
我有两个列表,一个参考和一个输入列表
Ref = [3, 2, 1, 12, 11, 10, 9, 8, 7, 6, 5, 4]
Input = [9, 5, 2, 3, 10, 4, 11, 8]
Run Code Online (Sandbox Code Playgroud)
我想按照 Ref 的顺序对输入列表进行排序。如果输入列表中缺少某个元素,它可以跳过并转到另一个元素。
因此排序的输入列表,基于参考列表将是这样的
Sorted_Input = [3, 2, 11, 10, 9, 8, 5, 4]
Run Code Online (Sandbox Code Playgroud) 我可以定义自己的排序顺序并仍然使用 Python 排序函数吗?例如,假设我想要的排序顺序是:
list1 = ['Stella', 'Bob', 'Joe', 'Betty']
Run Code Online (Sandbox Code Playgroud)
我希望做类似的事情:
list2 = ['Joe', 'Stella']
sorted(list2, key=list1)
Run Code Online (Sandbox Code Playgroud)
并得到:
['Stella', 'Joe']
Run Code Online (Sandbox Code Playgroud)
其中排序顺序保留在 中的自定义顺序内list1。我可以通过交换数值来分多个步骤来完成此操作,但我认为可能有一种方法可以与上面类似。