0

例如,我有一个元组列表。

[('ABC', 'Abcair', 1.50), ('DEF', 'Defir', 5.60), ('GHI', 'Ghiair',3.22), ('ANZ', 'Anzplace', 26.25), ('ARG', 'Argair', 12.22), ('CEN', 'Cenair', 11.22), ('CNU', 'Cununun',3.01)]

我有这样的输入命令

code_input = input('Please list portfolio: ').upper()

一个人将输入任意数量的用逗号分隔的 3 个字母代码,然后我将其格式化为

no_spaces_codes = code_input.replace(" ", "")
code_list = no_spaces_codes.split(",")

所以,"Ank , ABc,DEF"变成['ANK', 'ABC', 'DEF']

然后我打印这些标题格式化

header="{0:<6}{1:<20}{2:>8}".format("Code","Place","Number")
print(header)

然后,我需要在元组列表中搜索 3 个字母代码并打印标题下的值,格式相同,例如,不在列表中的代码将不会被打印。

Code  Name                   Price
ABC   Abcair                  5.30
DEF   Defair                 11.22

我已经走到这一步了。

for code in b:
    if code[0] == (code_list[1]):
        print(code[:])
        break

哪个打印

Code  Name                   Price
('CEN', 'Contact', 11.22)

但我不能比这更进一步。

4

2 回答 2

3

你可以这样做:

place, price = next((c[1:] for c in b if c[0] == code_input), ('Not found', 0))

但你真的想改用字典:

code_dict = {k: (v, p) for k, v, p in b}

之后匹配变成一个简单的查找:

place, price = code_dict.get(code_input, ('Not found', 0))

示范:

>>> b = [('ABC', 'Abcair', 1.50), ('DEF', 'Defir', 5.60), ('GHI', 'Ghiair',3.22), ('ANZ', 'Anzplace', 26.25), ('ARG', 'Argair', 12.22), ('CEN', 'Cenair', 11.22), ('CNU', 'Cununun',3.01)]
>>> code_input = 'CEN'
>>> place, price = next((c[1:] for c in b if c[0] == code_input), ('Not found', 0))
>>> print code_input, place, price
CEN Cenair 11.22
>>> code_dict = {k: (v, p) for k, v, p in b}
>>> place, price = code_dict.get(code_input, ('Not found', 0))
>>> print code_input, place, price
CEN Cenair 11.22

使用code_dict映射,在进行多次查找时查找会快得多,尤其是当列表中不存在条目时。将其与您的其余代码放在一起:

code_input = input('Please list portfolio: ').upper()
code_dict = {k: (v, p) for k, v, p in b}

line="{0:<6}{1:<20}{2:>8}"
print line.format("Code", "Place", "Number")

for code in code_input.split(','):
    code = code.strip()
    if code not in code_dict:
        continue  # skip codes not in the mapping
    place, price = code_dict[code]
    print line.format(code, place, price)

您的"Ank , ABc,DEF"输入将打印:

Code  Place                 Number
ABC   Abcair                   1.5
DEF   Defir                    5.6
于 2013-03-19T10:36:05.563 回答
1
result = [v for v in list_of_tuples if v[0] in code_list]
for v in result:
    print(v) # Or format 'v' tuple in any way you want.
于 2013-03-19T10:28:13.483 回答