您的代码似乎工作得很好:
>>> FList = ["Mary Smith", "Kevin Bacon"]
>>> JG = [[3928, "Mary Smith"], [2920, "Jacob Francis"], [7777, "Kevin Bacon"]]
>>> ultralist = []
>>> for item in FList:
for row in JG:
if row[1] == item:
ultralist.append(row)
>>> ultralist
[[3928, 'Mary Smith'], [7777, 'Kevin Bacon']]
出了什么问题?
当我这样做时,这将是一个更好的方法。您不需要两个 for 循环:
>>> FList = ["Mary Smith", "Kevin Bacon"]
>>> JG = [[3928, "Mary Smith"], [2920, "Jacob Francis"], [7777, "Kevin Bacon"]]
>>> ultralist = []
>>> for row in JG:
if row[1] in FList:
ultralist.append(row)
>>> ultralist
[[3928, 'Mary Smith'], [7777, 'Kevin Bacon']]
这种方法更简洁,使代码更容易理解。首先,您尝试对JG
: 执行操作,查找其中符合特定条件的元素。所以首先迭代JG
而不是迭代已经很清楚了FList
。然后,您可以使用快捷方式,而不是执行显式循环FList
以查看是否有任何名称匹配。无论如何,这在内部执行了一个 for 循环,但是很清楚代码的意图是什么。row[1]
row[1] in FList
更快的是使用set
for FList
:
>>> FList = set(["Mary Smith", "Kevin Bacon"])
>>> JG = [[3928, "Mary Smith"], [2920, "Jacob Francis"], [7777, "Kevin Bacon"]]
>>> ultralist = []
>>> for row in JG:
if row[1] in FList:
ultralist.append(row)
>>> ultralist
[[3928, 'Mary Smith'], [7777, 'Kevin Bacon']]
请注意,循环代码不会改变。不同的是,in
集合的操作比列表快得多。您不必遍历每个元素,而是进行一些花哨的哈希查找。
更好的是只使用列表理解:
>>> FList = set(["Mary Smith", "Kevin Bacon"])
>>> JG = [[3928, "Mary Smith"], [2920, "Jacob Francis"], [7777, "Kevin Bacon"]]
>>> ultralist = [row for row in JG if row[1] in FList]
>>> ultralist
[[3928, 'Mary Smith'], [7777, 'Kevin Bacon']]
这段代码更简洁,因此更容易理解。