如何搜索嵌套列表,查找“a”,然后将“a”旁边的“b”分配给变量?

问题描述 投票:0回答:2

通过用户输入我创建了一个嵌套列表

列表示例:

[[a, 1], [b, 2], [c, 3]]

ex:我的目标是找到“2”并将其分配给一个变量,但只用一个字母搜索它。

我通过让用户通过索引输入字母变量,然后将一个添加到索引来解决这个问题。下面是我尝试解决问题的两种方式的更多示例:

total_list
[['chloe', '2018'], ['camille', '2002'], ['hannah', '1979']]
(个别榜单为
peep_list

假设我想知道克洛伊是哪一年结婚的,所以我输入“克洛伊”。我正在尝试在列表中搜索名称,然后向右移动一个位置并保存该值。

person1 = str(input("Enter the name of the first person you would like to compare: "))

index = 0
age1 = 0

示例/尝试 1:

for peep_list in total_list:
    for person in peep_list:
        index(person1)
        age1 = index + 1

示例/尝试 2:

for peep_list in total_list: 
    for person in peep_list:
        if index == person1:
            age1 = index + 1
        else:
            index = index +1

我的做法是否正确?

python indexing nested-lists
2个回答
0
投票

total_list
由子列表组成。在每个子列表中,第一项是名称,第二项是年份。

因此,当您遍历

total_list
时,检查当前子列表中的第一项。如果它等于目标名称,则打印(或分配给另一个变量,或任何你喜欢的)子列表中的第二项。

name = 'chloe'

for sublist in total_list:
    if sublist[0] == name:
        print(name, 'was married in', sublist[1])

0
投票

你的

list
格式为
[[key, value],[key, value],...]
dict
可以使用这种格式投射
list
。通过转换为
dict
,您可以使用提供的名称作为键。

data = [['chloe', '2018'], ['camille', '2002'], ['hannah', '1979']]

db   = dict(data)

person = input("Enter the name of the first person you would like to compare: ")

print(db[person])

如果您只能使用“列表逻辑”来执行此操作,则以下是一种可能性。

data = [['chloe', '2018'], ['camille', '2002'], ['hannah', '1979']]

person = input("Enter the name of the first person you would like to compare: ")

for (name, year, *a) in data:
    if name == person:
        print(year)
        break

(name, year, *a)

你已经知道你的数据只有

name
year
,但如果你有更多的数据,它会全部转储到
(*a)rgs
。但是,没有更多数据不会破坏
args
args
在你的情况下只是空的。

© www.soinside.com 2019 - 2024. All rights reserved.