简体   繁体   English

如何在Python中从列表中打印单独的项目?

[英]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 我想从第一个数据数组中打印数字1、3、4我找不到如何打印它

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

how can I make it not to print 2 (I'm using python 3.2)?? 我怎样才能不打印2(我正在使用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: 如果您希望它打印不是数字2 data[0][0:4] ,则可以执行以下操作:

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: 如果要“切片” data[0][1] ,则可以将其周围的两个切片串联起来:

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] : 这也可以扩展为例如从[1:3]删除整个切片,而不仅仅是[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); 尽管对于删除不连续的组(如索引1、3或8中的任何内容)效果不佳; for that, you'd probably want enumerate . 为此,您可能需要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]

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

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