【问题标题】:Is there a simpler and efficient way to store n space delimited values in n different lists?有没有一种更简单有效的方法来将 n 个空格分隔的值存储在 n 个不同的列表中?
【发布时间】:2020-02-25 21:09:20
【问题描述】:
i,j,k = map(int, sys.stdin.readline().split())
a.append(i)
b.append(j)
c.append(k)

上面的代码可以正常工作,但我们可以用更简单有效的方式编写这段代码吗? 我正在遍历每行包含三个整数的 n 行,并希望为每行的第一个值、第二个值和第三个值创建三个单独的列表。

在英语中我想做这样的事情:

a.append(x) , b.append(y) 其中 x , y 在 sys.stdin.readline().split()

因此,我想读取一行并将值附加到单独的列表中,因此当我访问列表 a[] 时,它包含每行的第一个值

Input:
1 2 3
4 5 6
7 8 9
10 11 12


Output:
a
>> [1, 4, 7, 10]
b
>> [2, 5, 8, 11]
c
>> [3, 6, 9, 12]

【问题讨论】:

  • 你会读很多这样的行吗?
  • 请显示您的全部问题的minimal reproducible example 或更好地解释。你是说“每行有 3 个整数”,但只显示一行

标签: python python-3.x list append


【解决方案1】:

如果您需要对多行执行此操作,您可以解压缩生成器,将 所有 行作为参数转换为 zip,然后生成 tuple 的第一个元素每一行,然后是第二行元素的tuple,等等。

a, b, c = zip(*(map(int, line.split()) for line in f if line.strip()))

本质上,zip 将一堆产生“行”的迭代器转换成一个产生“列”的迭代器。拆分版本如下所示:

rows = (map(int, line.split()) for line in f if line.strip())
columns = zip(*rows)
a, b, c = columns

如果您希望结果为list,而不是tuple,您可以进一步将其包装为:

a, b, c = map(list, zip(*(map(int, line.split()) for line in f if line.strip())))

尽管此时它变得非常密集。

【讨论】:

  • a, b, c = map(list, zip(*(map(int, line.split()) for line in sys.stdin.read() if line.strip()))) print(a,b,c)读完n行后如何在这里终止循环?
  • @ChiragDamania:一,不要调用.read()(这会将整个文件作为单个字符串啜饮)。二、用itertools.islicen行,把sys.stdin.read()换成itertools.islice(sys.stdin, n)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-08-26
  • 1970-01-01
  • 1970-01-01
  • 2011-04-12
  • 2019-11-11
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多