简体   繁体   English

比较python中两个列表索引的方法

[英]way to compare between index of two lists in python

list1=['name1','name2','name3']
list2=[123,1234,12345]

i wanna say in python if index of 'name1'in the first list is equal to index of 123 in the second list without knowing them for example 'name1' and 123 is user input我想在 python 中说,如果第一个列表中 'name1' 的索引等于第二个列表中的 123 索引而不知道它们,例如 'name1' 和 123 是用户输入

i have tried many things like using .index but i get an error TypeError: list indices must be integers or slices, not str TypeError: list indices must be integers or slices, not str我已经尝试了很多东西,比如使用 .index 但我得到一个错误 TypeError: 列表索引必须是整数或切片,而不是 str TypeError: 列表索引必须是整数或切片,而不是 str

and tried many other things but none worked as i wanted并尝试了很多其他的东西,但没有一个像我想要的那样工作

You can do the following:您可以执行以下操作:

list1 = ['name1', 'name2', 'name3']
list2 = [123, 1234, 12345]

name = input("name: ")
num = int(input("num: "))  # don't forget to convert to int

if (name, num) in zip(list1, list2):
    print("Yay")
else:
    print("Aww")

Assuming they are the same length假设它们的长度相同

for count, data in enumerate(list1):
    if(list1[count] == list2[count]):
        print("yay")

If you just want to know if both lists contain the same data如果您只想知道两个列表是否包含相同的数据

for count, data in enumerate(list1):
    if(data in list2):
        print("yay")

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM