假设您有以下列表:
fruit_types = ["apple","pear","strawberry","mango"]
fruits = ["apple","strawberry","mango"]
我如何编写一个循环来标识“pear”元素缺失 “水果”榜单的第二个指数?
我知道第一步始于:
for element in fruit_types:
if element not in fruits:
但我完全失去了从这里出发的其他地方。
答案 0 :(得分:3)
以上设定的差异有效。但是如果你想要的代码只检查两个列表中的一个是否缺少元素(在你的风格中)。您可以使用枚举函数。
fruit_types = ["apple","pear","strawberry","mango"]
fruits = ["apple","strawberry","mango"]
def find_missing_index():
for index, element in enumerate(fruit_types):
if element not in fruits:
print(fruit_types[index], index)
def main():
find_missing_index()
if __name__ == '__main__':
main()
毫无疑问,您需要设置差异代码,但其中有很多其他例子。
为了提高性能,最好提前将fruits
转换为set
。
fset = set(fruits)
for index, element in enumerate(fruit_types):
if element not in fset:
print(fruit_types[index], index)
这会将成员资格测试减少为常量O(1)
查找。
答案 1 :(得分:1)
您可以在set
上使用差异操作来查找此内容。
fruit_types = ["apple","pear","strawberry","mango"]
fruits = ["apple","strawberry","mango"]
missings = list(set(fruits_types) - set(fruit))
print missings
如果这很酷,那么为什么要使用循环?
然后获取缺失项目的索引:
for missing in missings:
print fruit_types.index(missing)
答案 2 :(得分:0)
使用集差异,并找到索引:
fruit_types = ["apple","pear","strawberry","mango"]
fruits = ["apple","strawberry","mango"]
missings = set(fruit_types) - set(fruits)
for missing in missings:
print(fruit_types.index(missing))
1 # which is the index of the missing element in fruit_types
答案 3 :(得分:0)
你可以这样做:
fruit_types = ["apple","pear","strawberry","mango"]
fruits = ["apple","strawberry","mango"]
missing_elements = []
for element in fruit_types:
if(element not in fruits):
missing_elements.append(element)
print(missing_elements)
>>> ["pear"]
创建一个空列表,如果元素不在水果中,则添加到该列表。