如何访问lis中的列表

2024-04-29 14:54:01 发布

您现在位置:Python中文网/ 问答频道 /正文

如何访问列表中的值?地址:

list_ = [[Bob, 13, 156], [Jonny, 24, 180]]

假设我想找出18岁及以上的人,如果我找到了,我该如何打印出一个是年轻人还是老年人。你知道吗

我试过使用for-loops,但不起作用


Tags: 列表for地址listbob老年人loops年轻人
3条回答

如果列表中的列表长度相同,那么下面的解决方案就是工作

for x in enumerate (list):
    if x[1] >= 18:
        print(x[0])

列表理解单行代码

[x[0] for x in list if x[1] >= 18]

你可以这样做


ls = [["Bob", 13 ,156], ["Jonny", 24, 180]]

## this line loops through the ls and unpack the 3 values to variable names
## name, age and value. condition "if age>=18" filters user matching the condition  
_18_or_above = [name for name, age, value in ls if age>=18]

print(_18_or_above)

## this lines sort the list by first element of list item which is age
sorted_by_age = sorted(ls, key=lambda x: x[1])

print(sorted_user)

您只需执行索引的索引。你知道吗

例如在嵌套列表中

              [0]                 [1]
          [0]   [1]  [2]     [0]    [1]  [2]
list = [['Bob', 13 ,156], ['Jonny', 24, 180]]

list[0][0] = 'Bob'
list[1][2] = 180

循环通过也是一样的 例如

for i in list:
    age = i[1]
    if age > 18:
        print("Age is greater than 18", i)

相关问题 更多 >