python - extracting a range of elements from a csv / 2d array -


i want extract elements range of elements specific column csv file.

i've simplified problem 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 meant

  • 'show me columns row 0 , 1'
  • 'show me rows column 0 , 1'

but output showing me rows 0 , 1, never columns,

[['a', 1, 'a', 100], ['b', 2, 'b', 200]]  rows 0&1 [['a', 1, 'a', 100], ['b', 2, 'b', 200]]  cols 1&1 

when want see this:

['a', 1, 'a', 100,'b', 2, 'b', 200]  # ... i.e. rows 0 , 1 ['a','b','c','d',1,2,3,4] 

is there nice way this?

your problem here data[:] 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]] 

... both attempts @ slicing giving same result data[0:2].

you can columns 0 , 1 list comprehension:

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

... can rearranged order want zip():

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

to single list rather list of 2 tuples, use itertools.chain.from_iterable():

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

... can used collapse data[0:2]:

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

Comments

Popular posts from this blog

c++ - OpenCV Error: Assertion failed <scn == 3 ::scn == 4> in unknown function, -

php - render data via PDO::FETCH_FUNC vs loop -

The canvas has been tainted by cross-origin data in chrome only -