Domanda

I have a problem trying to find and get and array from a bi dimensional array in python. I don't pretend to use a for structure for example in order to get this. Someone knows how to get this array in just one or a few lines of code?.

Thanks.

There is an example:

my_dimensional_array = [(1,'a'),(1,'b'),(2,'c'))]

I need to return

my_single_array_from_1 = [(1,'a'),(1,'b')]
È stato utile?

Soluzione

You could use a list comprehension to select those elements in my_dimensional_array whose first value equals 1:

In [16]: my_dimensional_array = [(1,'a'),(1,'b'),(2,'c')]

In [17]: [item for item in my_dimensional_array if item[0]==1]
Out[17]: [(1, 'a'), (1, 'b')]

Altri suggerimenti

If you just want to exclude the last element, you can use slicing like this

my_dimensional_array = [(1, 'a'), (1, 'b'), (2, 'c')]
print my_dimensional_array[:-1]
# [(1, 'a'), (1, 'b')]

You can do that as:

result = [(i,j) for i,j in my_dimensional_array if i==1]
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top