Reputation: 260
I suspect there are more than one ways to do this in Python 2.7, but I'd like to be able to print the first three elements of each sublist in combos. Is there a way to do this without a loop?
combos = [ [1,2,3,.14], [5,6,7,.18], [9,10,11,.12], [1,2,3,.15] ]
such that the output of a print statement would read:
[ [1,2,3], [5,6,7], [9,10,11], [1,2,3] ]
***AFTER GETTING YOUR SUGGESTIONS: I was struggling to see how this would work inside of my code structure but list comprehension can be done as part of an if statement like so, which I failed to recognize:
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]
The output:
p0 found
[0.15]
Thanks all.
Upvotes: 0
Views: 93
Reputation: 63757
I suspect there are more than one ways to do this in Python 2.7
Yes and you can be quite creative with it. This is another alternative
from operator import itemgetter
map(itemgetter(slice(3)), combos)
Out[192]: [[1, 2, 3], [5, 6, 7], [9, 10, 11], [1, 2, 3]]
Upvotes: 0