[英]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:
From here we want to find the Index of "User", lets go with Kat, I know it's 1, 0,从这里我们想找到“用户”的索引,让 go 与 Kat,我知道它是 1、0,
However I want the program to be able to tell me for what ever name is entered, this way I than can print但是我希望程序能够告诉我输入了什么名字,这样我就可以打印了
(User + '\'s', 'age is', (ExampleListFull(variable) (variable)))
I would recommend you to use a dictionary as you data structure here but is you need a list you could try using the index method as follow:我建议您在这里使用字典作为数据结构,但是您是否需要一个列表,您可以尝试使用 index 方法,如下所示:
ExampleList = [['Ck'], ['Kat'], ['Arcadiusz']]
x = ExampleList.index(['Ck'])
print(x)
Output: Output:
0
This returns the position at the first occurrence of the specified value这将在第一次出现指定值时返回 position
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()
Here, we create a dummy list with the values of all the names.在这里,我们创建了一个包含所有名称值的虚拟列表。 This should print
['CK', 'Kat', 'Arcadiusz']
这应该打印
['CK', 'Kat', 'Arcadiusz']
names = [value[0] for value in data]
print(names)
The one-line for-loop is the equivalent of doing:单行 for 循环相当于执行以下操作:
names = []
for value in data:
names.append(value[0])
Then we can print the result然后我们可以打印结果
print(names.index(name))
print("Age is", {data[names.index(name)][1]})
This can all be shortened to just a few lines of code like this:这一切都可以缩短为几行代码,如下所示:
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]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.