简体   繁体   中英

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.

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'
  • 'show me all the rows for just column 0 and 1'

But the output is always just showing me rows 0 and 1, never the columns,

[['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
[['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] .

You can get just columns 0 and 1 with a list comprehension:

>>> [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() :

>>> 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() :

>>> 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] :

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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