如何读取.txt文件并将某些行存储为列表作为变量列表? [蟒蛇]

时间:2015-01-22 07:54:48

标签: python list

例如,如果给我一个化学实验教程,材料清单如下:

9 mL water
20 L acid

如何将列表列表中的材料存储为[[9," mL"," water"],[20," L", "酸"。]]

2 个答案:

答案 0 :(得分:1)

with open("filename.txt") as f:
    splitted = [line.split() for line in f]
result = [[int(words[0])] + words[1:] for words in splitted]

如果数字不总是整数,请使用float代替int

答案 1 :(得分:0)

您可以使用带分割线的条带拆分:

s = """9 mL water 
       20 L acid"""

print [r.strip().split(' ') for r in s.splitlines()]

<强>结果:

[['9', 'mL', 'water'], ['20', 'L', 'acid']]