我需要打破对值的线条并将其转换为列表或dictonary。有没有人知道在Python中使用这种方法的简单方法?
由此:
1
Petrov
2
Ivanov
3
Sidorov
到
["1", "Petrov"], ["2", "Ivanov"], ["3", "Sidorov"]
或dictonary:
{"1": "Petrov", "2": "Ivanov", "3": "Sidorov"}
答案 0 :(得分:3)
>>> strs = """1
Petrov
2
Ivanov
3
Sidorov"""
>>> dict(zip(*[iter(strs.splitlines())]*2))
{'2': 'Ivanov', '3': 'Sidorov', '1': 'Petrov'}
答案 1 :(得分:0)
此代码将返回字典:
inp = open("file")
d = dict()
k = list()
v = list()
for line in inp:
if line.strip("\n").isdigit():
k.append(line.strip("\n"))
else:
v.append(line.strip("\n"))
print dict(zip(k,v))
答案 2 :(得分:0)
通过操纵列表中的奇数和偶数项,为hcwhsa的解决方案添加一点点扭曲:
>>> s = "1\nPetrov\n2\nIvanov\n3\nSidorov"
>>> dict(zip(s.split("\n")[::2], s.split("\n")[1::2]))
{'1': 'Petrov', '3': 'Sidorov', '2': 'Ivanov'}
请参阅Shortest way to slice even/odd lines from a python array?
答案 3 :(得分:0)
>>> strs = """1
Petrov
2
Ivanov
3
Sidorov"""
>>> i = iter(strs.split())
>>> {item: i.next() for item in i}
{'1': 'Petrov', '3': 'Sidorov', '2': 'Ivanov'}
或
>>> i = iter(strs.split())
>>> [[item, i.next()] for item in i]
[['1', 'Petrov'], ['2', 'Ivanov'], ['3', 'Sidorov']]