Python:List1的索引等于List2的索引
我有2个列表,它们的长度相同且按顺序正确,我需要(我认为)List1的索引等于List2的索引,并在该索引上打印List2内容。
这就是我到目前为止所拥有的:
id = [10610, 12772, 10611, 13434, 13397, 13854]
name = ['sarah', 'john', 'mark', 'james', 'jack']
userid = int(input('enter user ID: '))
ind = id.index(userid)
if userid in id:
print(ind)
else:
print('wrong ID')
输出:
enter user ID: 13434
3
我想做的就是打印在“名称”列表中相同索引的内容,在这种情况下为“詹姆斯”
谢谢
I have 2 lists , they are the same length and in correct order, what i need(i think) is that index of list1 is equal to index of list2 and print the list2 content at that index.
this is what i have so far:
id = [10610, 12772, 10611, 13434, 13397, 13854]
name = ['sarah', 'john', 'mark', 'james', 'jack']
userid = int(input('enter user ID: '))
ind = id.index(userid)
if userid in id:
print(ind)
else:
print('wrong ID')
output:
enter user ID: 13434
3
what i want it to do is, to print the content thats at the same index in "name" list, in this case its "james"
thanks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
好吧,评论所说的内容也像以下内容一样更改:
如果您尝试在检查ID(他们输入的一个)之前尝试使用Inden(..),那么您将获得
valueerror:<一些numer>不在列表
中,所以最好在IF中进行操作
well what the comments said and change it like the following too :
if you try to use inden(..) before checking if the userid (the one they entered) is in the id , then you will get
ValueError: <some-numer> is not in list
so its better to do it inside the if
您需要做的就是执行以下操作:
All you need to do is do the following:
由于要从
name
在同一索引上打印字符串,因此可以使用name [ind]
。不过,上面给出的代码还有其他问题 -
ind = id.index(userId)
将给出valueerror
如果userId
在id> id
list中不存在,程序将崩溃。这可以重构为以下内容:ID
和name
中的NO元素并不相同。这可能会导致indexError
当输入为13854时。可以通过检查len(name)&lt来解决这一点。 Ind
Since you want to print the string from
name
at the same index, you can usename[ind]
.Though, there are some other issues with the code given above -
ind = id.index(userid)
would give aValueError
ifuserid
isn't present in theid
list, and the program would crash. This can be refactored to the following:id
and inname
isn't the same. This can lead to anIndexError
when the input is 13854. This can be resolved by checking iflen(name) < ind