简体   繁体   English

从csv / 2d数组中提取一系列元素

[英]extracting a range of elements from a csv / 2d array

I want to extract elements from a range of elements is a specific column from a csv file. 我想从一系列元素中提取元素是csv文件中的特定列。

I've simplified the problem to this: 我已将问题简化为:

data = [['a',1,'A',100],['b',2,'B',200],['c',3,'C',300],['d',4,'D',400]]

print(data[0:2][:],'\nROWS 0&1')
print(data[:][0:2],'\nCOLS 1&1')

I thought that meant 我以为那意味着

  • 'show me all columns for just row 0 and 1' “仅显示第0行和第1行的所有列”
  • 'show me all the rows for just column 0 and 1' “仅显示第0列和第1列的所有行”

But the output is always just showing me rows 0 and 1, never the columns, 但是输出总是只显示0行和1行,而不显示列,

[['a', 1, 'A', 100], ['b', 2, 'B', 200]] 
ROWS 0&1
[['a', 1, 'A', 100], ['b', 2, 'B', 200]] 
COLS 1&1

when I want to see this: 当我想看到这个时:

['a', 1, 'A', 100,'b', 2, 'B', 200]  # ... i.e. ROWS 0 and 1
['a','b','c','d',1,2,3,4]

Is there a nice way to do this? 有没有很好的方法可以做到这一点?

Your problem here is that data[:] is just a copy of data : 您的问题是data[:]只是data 的副本

>>> data
[['a', 1, 'A', 100], ['b', 2, 'B', 200], ['c', 3, 'C', 300], ['d', 4, 'D', 400]]
>>> data[:]
[['a', 1, 'A', 100], ['b', 2, 'B', 200], ['c', 3, 'C', 300], ['d', 4, 'D', 400]]

... so both your attempts at slicing are giving you the same result as data[0:2] . ...因此,您进行切片的两次尝试都将获得与data[0:2]相同的结果。

You can get just columns 0 and 1 with a list comprehension: 您可以通过列表理解仅获得列0和1:

>>> [x[0:2] for x in data] 
[['a', 1], ['b', 2], ['c', 3], ['d', 4]]

... which can be rearranged to the order you want with zip() : ...可以使用zip()重新排列为所需的顺序:

>>> list(zip(*(x[0:2] for x in data)))
[('a', 'b', 'c', 'd'), (1, 2, 3, 4)]

To get a single list rather than a list of 2 tuples, use itertools.chain.from_iterable() : 要获得一个列表而不是两个元组的列表,请使用itertools.chain.from_iterable()

>>> from itertools import chain
>>> list(chain.from_iterable(zip(*(x[0:2] for x in data))))
['a', 'b', 'c', 'd', 1, 2, 3, 4]

... which can also be used to collapse data[0:2] : ...也可以用于折叠data[0:2]

>>> list(chain.from_iterable(data[0:2]))
['a', 1, 'A', 100, 'b', 2, 'B', 200]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM