Home > Mobile >  How to iterate and print each element in list (Python)
How to iterate and print each element in list (Python)

Time:09-21

arr(['36 36 30','47 96 90','86 86 86']

I want to store and print the values like this,

36
36 
30
47
...

How do I do this using python?

CodePudding user response:

the simplest way is to use for and str.split()

arr=['36 36 30','47 96 90','86 86 86']
for block in arr:
    cells = block.split()
    for cell in cells: 
        print(cell)

prints

36
36
30
47
96
90
86
86
86

you can also use a list comprehension like so, which returns the same result.

print("\n".join([ele for block in arr for ele in block.split()]))

CodePudding user response:

You can use lists and split in python. Try in this way:

arr = ['36 36 30','47 96 90','86 86 86']
for i in arr:
    elems = i.split()
    for elem in elems:
        print(elem)

CodePudding user response:

We can try the following approach. Build a single string of space separated numbers, split it, then join on newline.

inp = ['36 36 30', '47 96 90', '86 86 86']
output = '\n'.join(' '.join(inp).split())
print(output)

This prints:

36
36
30
47
96
90
86
86
86

CodePudding user response:

You can split your values up and convert them into a flat list, from there you can easily loop and print.

data = ['36 36 30','47 96 90','86 86 86']
output = [num for data in [nums.split() for nums in data] for num in data]

for number in output:
  print(number)

Outputs

36
30
47
96
90
86
86
86

print(output)
['36', '36', '30', '47', '96', '90', '86', '86', '86']
  • Related