-2

Hi I would like to check if there is any way to get subitem on a array for example below.

Array = [('a',1,'aa'),('b',2,'bb'),('c',3,'cc')]

If would like to print out all 2nd subitem for Array like this [ 1, 2, 3]

Or maybe 3rd subitem like this [ aa , bb, cc]

Please help me... Thank you so much

Yonlif
  • 1,770
  • 1
  • 13
  • 31
  • Use a loop then get then second or third element from each tuple inside your list. Also, make sure that the tuple inside have enough length to perform such operation – Chiheb Nexus Jul 01 '17 at 18:08

4 Answers4

0

You can use list-comprehension in a function like:

def get_elem(arr, n):
    return [x[n] for x in arr]

then call it:

my_array = [('a', 1, 'aa'), ('b', 2, 'bb'), ('c', 3, 'cc')]
print get_elem(my_array, 1)

output:

[1, 2, 3]
Mohd
  • 5,523
  • 7
  • 19
  • 30
0

Python is designed at it's core to handle this tasks very easily. You don't need loops to merge, extract, split, lists.

List comprehensions are great to do this kind of operations on containers.

Generator expressions can be even more useful, usage depends on the context.

Here is an example of both:

array = [('a',1,'aa'), ('b',2,'bb'), ('c',3,'cc')]
sub_2 = [item[2] for item in array] # sub_2 is a classique list, with a length
gen_1 = (item[1] for item in array) # gen_1 is a generator, which gather value on the fly when requested

print(sub_2)
for i in gen_1:
    print(i)

Output:

['aa', 'bb', 'cc']
1
2
3

You can write a utility function to help, but in simple cases, it's probably better to directly write the generator where you need it.

Here is an example of utility function you could write:

def sub(container, index):
    return (item[index] for item in container)

print([i for i in sub(array, 0)])

Outputs ['a', 'b', 'c']

johan d
  • 2,798
  • 18
  • 26
-1

You can do this by creating a function to get the nth item in a tuple (or list), then calling that function inside a loop like so:

my_array = [('a', 1, 'aa'), ('b', 2, 'bb'), ('c', 3, 'cc')]
result_array = []
n = 2 # set your desired index here

def get_nth(some_tuple, index):
    result_array.append(some_tuple[index] if len(some_tuple) > index else None)

for sub_item in my_array:
    get_nth(sub_item, n)

print result_array
RemedialBear
  • 644
  • 5
  • 15
-1

Use zip:

Array = [ ('a',1,'aa'),('b',2,'bb'),('c',3,'cc') ]
zipped = zip(*Array) #gives your desired form
for item in zipped:
    print(item)

Output:

('a', 'b', 'c')
(1, 2, 3)
('aa', 'bb', 'cc')
Sam Chats
  • 2,271
  • 1
  • 12
  • 34