从输入中拆分并追加到2个数组

时间:2018-05-14 05:39:10

标签: python python-2.7 dictionary split

我想要这样的东西。字符串 - >拆分 - >追加每个而不创建新的2个变量(或1个列表)

a=[]
b=[]
sum = 0;

for i in range(n):
    map(lambda x, y: a.append(x),b.append(y),raw_input().split(" "));

是的,那不起作用couse append return null。 但那太丑了。

for i in range(n):
    buf = map(int,raw_input().split(" "));
    a.append(buf[0])
    b.append(buf[1])

1 个答案:

答案 0 :(得分:0)

第二种方法没有错。事实上它很清楚它的作用。您可以使用元组解包来使它看起来更好一些:

for i in range(n):
    first, second = map(int, raw_input().split(" "));
    a.append(first)
    b.append(second)

如果您仍然希望将其作为一个单行,那么您可以采用不同的示例进行示例处理:

t = ['A B', 'C D', 'E F']
a, b = zip(*(i.split() for i in t))

>>> print(a)
('A', 'C', 'E')
>>> print(b)
('B', 'D', 'F')