简体   繁体   中英

Using a for-loop, in another for-loop, to iterate through a list of lists

I'd like to write a set of for-loops that iterate through a list of lists as shown below.

pathways = ['pathway_1','pathway_2']

pathway_1 = ['gene_A', 'gene_B']
pathway_2 = ['gene_C', 'gene_D']

for i in pathways:
    for ii in i:
          print(ii)

I'd like the output to look like this:

gene_A
gene_B
gene_C
gene_D

but currently generates this:

p
a
t
h
w
a
y
_
1
p
a
t
h
w
a
y
_
2

Is there a simple way of achieving this?

You cannot use strings variable s, so remove '' , else you loop by letters from strings in pathways list:

pathways = [pathway_1,pathway_2]

In the outside loop you are looping over a string and not a list, change the code like this:

pathway_1 = ['gene_A', 'gene_B']
pathway_2 = ['gene_C', 'gene_D']

pathways = [pathway_1, pathway_2]

for i in pathways:
    for ii in i:
          print(ii)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM