例如,如果给我一个化学实验教程,材料清单如下:
9 mL water
20 L acid
如何将列表列表中的材料存储为[[9," mL"," water"],[20," L", "酸"。]]
答案 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']]