简体   繁体   中英

Python: create a list of lists from a file

File:

 1 2,5 3,1
 2 4,10 1,5
 3 4,1 1,1
 4 2,10 3,1

I'd like to create dictionary as follows:

{1:[[2,5], [3,1]], 2:[[4,10], [1,5]], 
 3: [[4,1], [1,1]], 4: [[2,10], [3,1]]}

I managed to achieve this:

{1: [['2,5'], ['3,1']], 2: [['4,10'], ['1,5']], 
 3: [['4,1'], ['1,1']], 4: [['2,10'], ['3,1']]}

Using the following code:

f = open("file.txt")
D = {}

for line in f:
    line = line.strip().split(" ")   
    for i in line:
        D[int(line[0])] = [[x] for x in line[1:]]
print D
f = open("file.txt")
D = {}

for line in f:
    line = line.strip().split(" ")   
    for i in line:
        D[int(line[0])] = [[int(y) for y in x.split(',')] for x in line[1:]]
print D

Edit: tested. Should work fine :)

Because your original code contains a list comprehension I'm going to assume you understand them. All I did was turn [x] into [int(y) for y in x.split(',')] . Ie, ['3,4'] ->[3,4] .

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