简体   繁体   中英

How do I print separate items from list in Python?

for example I have a list

data=[[1, 2, 3, 4, 5, 6, 7], [2, 4, 3, 6, 5]]

I want to print numbers 1, 3, 4 from the first array of data I can't find how can i print it My code so far

print(data[0][0:4])

how can I make it not to print 2 (I'm using python 3.2)??

In [288]: data=[[1, 2, 3, 4, 5, 6, 7], [2, 4, 3, 6, 5]]

In [289]: for i in [0,2,3]:
   .....:     print(data[0][i], end=' ')
   .....:     
1 3 4 
print([data[0][0]] + data[0][2:4])

If you want it to print everything from data[0][0:4] that isn't the number 2 , you can do this:

print([x for x in data[0][0:4] if x != 2])

This can be extended to, eg, not print even numbers:

print([x for x in data[0][0:4] if x % 2 != 0])

If you want to "slice around" whatever's in data[0][1] , you can just concatenate the two slices around it:

print(data[0][0:1] + data[0][2:4])

This can also be extended to, eg, remove the whole slice from [1:3] instead of just [1:2] :

print(data[0][0:1] + data[0][3:4])

Although it doesn't work as well for removing discontiguous groups (like whatever's in index 1, 3, or 8); for that, you'd probably want enumerate .

如果要忽略某些索引,可以使用enumerate

" ".join([str(i) for ind,i in enumerate(data[0][0:4]) if ind != 1])

Here's my take on it:

>>> import pyexcel as pe
>>> data=[[1,2,3,4,5,6,7],[2,4,3,6,5]]
>>> m=pe.sheets.MultipleFilterableSheet(data)
>>> # get rid of other columns
>>> m.filter(pe.filters.ColumnFilter([1,4,5,6]))
>>> print(pe.utils.to_array(m))
[[1, 3, 4], [2, 3, 6]]
>>> print m.row[0]
[1, 3, 4]
>>> print m.row[0][0:3]
[1, 3, 4]

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