如何在列表的子列表中查找项目的索引 (python)
How to Find the Index of an Item in a sublist of a list (python)
ExampleList = [['Ck'], ['Kat'], ['Arcadiusz']]
ExampleListFull = [['CK', 21, 'Male'], ['Kat', 19, 'Female'], ['Arcadiusz', 30, 'Male']]
User = str(input())
User = User.capitalise()
if ([User] in ExampleList) == True:
从这里我们想找到“用户”的索引,让我们用Kat,我知道它是1、0,
但是我希望程序能够告诉我名字是什么
输入,这样我就可以打印
(User + '\'s', 'age is', (ExampleListFull(variable) (variable)))
我建议您在这里使用字典作为数据结构,但如果您需要一个列表,您可以尝试使用如下索引方法:
ExampleList = [['Ck'], ['Kat'], ['Arcadiusz']]
x = ExampleList.index(['Ck'])
print(x)
输出:
0
这个returns指定值第一次出现的位置
ExampleList = [['Ck'], ['Kat'], ['Arcadiusz']]
ExampleListFull = [['CK', 21, 'Male'], ['Kat', 19, 'Female'], ['Arcadiusz', 30, 'Male']]
User = str(input())
User = User.capitalize()
for Index,string in enumerate(ExampleList):
if User == ExampleList[Index][0]:
print(User + 's', 'age is ' + str(ExampleListFull[Index][1]))
ExampleListFull = [['CK', 21, 'Male'], ['Kat', 19, 'Female'], ['Arcadiusz', 30, 'Male']]
User = str(input())
User = User.capitalise()
在这里,我们创建了一个包含所有名称值的虚拟列表。这应该打印 ['CK', 'Kat', 'Arcadiusz']
names = [value[0] for value in data]
print(names)
一行for循环相当于做:
names = []
for value in data:
names.append(value[0])
然后我们可以打印结果
print(names.index(name))
print("Age is", {data[names.index(name)][1]})
这一切都可以缩短为几行代码,如下所示:
data = [['CK', 21, 'Male'], ['Kat', 19, 'Female'], ['Arcadiusz', 30, 'Male']]
User = str(input())
User = User.capitalise()
age = data[[value[0] for value in data].index(name)][1]
# gender= data[[value[0] for value in data].index(name)][2]