切片每个子列表中的一系列元素?
Slicing a range of elements in each sublist?
我怀疑在 Python 2.7 中有不止一种方法可以做到这一点,但我希望能够以组合方式打印每个子列表的前三个元素。有没有办法在没有循环的情况下做到这一点?
combos = [ [1,2,3,.14], [5,6,7,.18], [9,10,11,.12], [1,2,3,.15] ]
这样 print 语句的输出将显示为:
[ [1,2,3], [5,6,7], [9,10,11], [1,2,3] ]
***在收到您的建议后:
我一直在努力看看这在我的代码结构中是如何工作的,但是列表理解可以作为 if 语句的一部分来完成,但我没有意识到:
p0combos = [ [1,2,3,.14], [5,6,7,.18], [9,10,11,.12], [1,2,3,.15] ]
p0 = [1, 2, 3]
if p0 not in [combo[:3] for combo in p0combos]:
print combo[:3]
print 'p0 not found'
else:
print 'p0 found'
print combo[3:4]
输出:
p0 found
[0.15]
谢谢大家。
[sublist[:3] for sublist in combos]
print [temp_list[:3] for temp_list in combos]
I suspect there are more than one ways to do this in Python 2.7
是的,你可以很有创意。这是另一种选择
from operator import itemgetter
map(itemgetter(slice(3)), combos)
Out[192]: [[1, 2, 3], [5, 6, 7], [9, 10, 11], [1, 2, 3]]
我怀疑在 Python 2.7 中有不止一种方法可以做到这一点,但我希望能够以组合方式打印每个子列表的前三个元素。有没有办法在没有循环的情况下做到这一点?
combos = [ [1,2,3,.14], [5,6,7,.18], [9,10,11,.12], [1,2,3,.15] ]
这样 print 语句的输出将显示为:
[ [1,2,3], [5,6,7], [9,10,11], [1,2,3] ]
***在收到您的建议后: 我一直在努力看看这在我的代码结构中是如何工作的,但是列表理解可以作为 if 语句的一部分来完成,但我没有意识到:
p0combos = [ [1,2,3,.14], [5,6,7,.18], [9,10,11,.12], [1,2,3,.15] ]
p0 = [1, 2, 3]
if p0 not in [combo[:3] for combo in p0combos]:
print combo[:3]
print 'p0 not found'
else:
print 'p0 found'
print combo[3:4]
输出:
p0 found
[0.15]
谢谢大家。
[sublist[:3] for sublist in combos]
print [temp_list[:3] for temp_list in combos]
I suspect there are more than one ways to do this in Python 2.7
是的,你可以很有创意。这是另一种选择
from operator import itemgetter
map(itemgetter(slice(3)), combos)
Out[192]: [[1, 2, 3], [5, 6, 7], [9, 10, 11], [1, 2, 3]]