简体   繁体   中英

Python appending to a list from a string with the same name

I have the following list.

('A', 'Steve', 'AAPLES', '0', '0', '15')
('B', 'Steve', 'ORANGES', '0', '0', '100')
('C', 'Paul', 'GRAPES', '0', '0', '500')

I want to loop through each line and then append the line to a list with the same name as line[0].

I am trying something like:

A = []
B = []
C = []

for line in test_file:
    group = line[0].strip(' ')
    group.append(line)

This isn't working because 'group' is an string. can I make group a non string so I can append to that list?

Using a dictionary that map names to a lists:

A = []
B = []
C = []

group_dict = {'A': A, 'B': B, 'C': C}

for line in test_file:
    group = line.strip()[0]
    group_dict[group].append(line)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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