简体   繁体   English

列出包含 python 中的值的元素

[英]List the elements containing the value in python

I am trying to print out the list which contains a specific value.我正在尝试打印出包含特定值的列表。

fullint = []
students = [['Harry', 37.21], ['Berry', 37.21], ['Tina', 37], ['Akriti', 41], ['Harsh', 39]]
for k in students:
    fullint.append(k[1])

 fullint.sort()
 valuetobefound = fullint[1]

Here the valuetobefound variable contains the value 37.21.这里 valuetobefound 变量包含值 37.21。 All I want is to print the list ['Harry', 37.21], ['Berry', 37.21] which contains the value 37.21 inside students list.我想要的只是打印列表['Harry', 37.21], ['Berry', 37.21] ,其中包含学生列表中的 37.21 值。 I have tried我努力了

for valuetobefound in students:
    print(valuetobefound)

But this output returns all the lists ['Harry', 37.21], ['Berry', 37.21], ['Tina', 37], ['Akriti', 41], ['Harsh', 39] instead of ['Harry', 37.21], ['Berry', 37.21] .但是这个 output 返回所有列表['Harry', 37.21], ['Berry', 37.21], ['Tina', 37], ['Akriti', 41], ['Harsh', 39]而不是['Harry', 37.21], ['Berry', 37.21] All I need is the list containing the value 37.21.我只需要包含值 37.21 的列表。 Can anyone please guide me or tell me the logic to achieve this?.. Any help would be appreciated.谁能指导我或告诉我实现这一目标的逻辑?..任何帮助将不胜感激。 Thank you.谢谢你。

You can try like this:你可以这样尝试:

students = [['Harry', 37.21], ['Berry', 37.21], ['Tina', 37], ['Akriti', 41], ['Harsh', 39]]

some_list = []
for k in students:
    if k[1] == 37.21:
        some_list.append(k)
        
print(some_list) #[['Harry', 37.21], ['Berry', 37.21]]

After that some_list should contain what you want.之后some_list应该包含你想要的。

You can use list comprehension to achieve this result, filtering out every tuple that doesn't match your needs.您可以使用列表推导来实现此结果,过滤掉每个与您的需求不匹配的元组。

>>> students = [['Harry', 37.21], ['Berry', 37.21], ['Tina', 37], ['Akriti', 41], ['Harsh', 39]]
>>> my_val = 37.21
>>> students_match = [(stud, val) for (stud, val) in students if val == my_val]
>>> students_match
[('Harry', 37.21), ('Berry', 37.21)]

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

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