简体   繁体   English

Python。 如何根据列表中的选定变量找出元素的顺序

[英]Python. The way how to find out the element's order based on selected variable in list

I would find out the order of element in the list, which is selected based on any variable.我会找出列表中元素的顺序,它是根据任何变量选择的。

I have variables: first "users", where are names of poeple and second "values", where are any values of the people (just values which belong to names of list).我有变量:第一个“用户”,其中是人名和第二个“值”,其中是人的任何值(只是属于列表名称的值)。 Then i created another variable and in this variable I choose, which one of the elements will be printed to terminal.然后我创建了另一个变量,并在这个变量中选择,其中一个元素将打印到终端。 The variable "fer" I found on the internet and I don't understand excatly what is it doing.我在互联网上找到的变量“fer”,我不明白它在做什么。 I'm confused now.我现在很困惑。 I hope, it was understandable, that where's the problem.我希望,这是可以理解的,问题出在哪里。

Here is any code:这是任何代码:

users=['Peter', "Georgo", "Mike"]
values=[600, 700, 800]

print("Users: {}\nTheir Values: {}".format(users,values))

vstup=str(input("Choose the user: "))

if vstup == "Peter":
    val=values[0]
if vstup == str("Georgo"):
    val=values[1]
if vstup == "Mike":
    subs=str(values[2])

fer = list(filter(lambda x: vstup in x, users)) 
print("Selected: " + str(fer))
print("His value is: {}.".format(values[0]))

Are you looking for which position "Peter" or "Georgo" are in the list?您是否正在寻找列表中的 position “Peter”或“Georgo”? is so use the.count method like so就是这样使用.count方法

count = users.count(vstup)
print(count)

This will print their position as base 0这会将他们的 position 打印为 base 0

If your looking to print the correct value base on position, you simply need to如果您希望打印基于 position 的正确值,您只需要

print(val)

as you set them in the if statements当您在 if 语句中设置它们时

You can directly use the index function, so ind = users.index('Mike') is 2, and values[ind] is 800.可以直接使用index function,所以ind = users.index('Mike')为 2, values[ind]为 800。

You should look at dictionaries instead.你应该看字典。 They fit better, work faster, and are easier to type:它们更合身,工作更快,更容易打字:

users = { 'Peter': 600, 'Georgeo': 700, 'Mike': 800  }
print(f'Names = {list(users.keys())}')
print(f'Values = {list(users.values())}')
print(f'Georgeo number : {users["Georgeo"]}')
for user, value in users.items():
   print(f' {user} has {value}')

gives

Names = ['Peter', 'Georgeo', 'Mike']
Value = [600, 700, 800]
Georgeo number : 700
 Peter has 600
 Georgeo has 700
 Mike has 800

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

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