如何使用 while 循环访问列表的所有第二个元素,这些元素是存储在字典中的值?

How do I use a while loop to access all the 2nd elements of lists which are the values stored in a dictionary?

如果我有这样的字典,其中充满了类似的列表,我如何应用 while loo tp 提取一个打印第二个元素的列表:

racoona_valence={}
racoona_valence={"rs13283416": ["7:87345874365-839479328749+","BOBB7"],\}

我需要在更大的字典中为列表的第二个元素打印“BOBB7”部分。里面有十个键值对,所以我是这样开始的,但不确定该怎么做,因为我能找到的所有例子都与我的问题无关:

n=10
gene_list = []
while n>0:

非常感谢任何帮助。

这里有一个 list comprehension 可以满足您的需求:

second_element = [x[1] for x in racoona_valence.values()]

这里有一个 for loop 可以满足您的需求:

second_element = []
for value in racoona_valence.values():
    second_element.append(value[1])

这里有一个 while loop 可以满足您的需求:

# don't use a while loop to loop over iterables, it's a bad idea
i = 0
second_element = []
dict_values = list(racoona_valence.values())
while i < len(dict_values):
    second_element.append(dict_values[i][1])
    i += 1

无论您使用哪种方法,您都可以通过执行以下操作查看结果:

for item in second_element:
    print(item)

对于您给出的示例,这是输出:

BOBB7

好吧,有很多方法可以做到这一点,具体取决于数据的结构。

racoona_valence={"rs13283416": ["7:87345874365-839479328749+","BOBB7"], "rs13283414": ["7:87345874365-839479328749+","BOBB4"]}
output = []
for key in racoona_valence.keys():
    output.append(racoona_valence[key][1])
print(output)

other_output = []
for key, value in racoona_valence.items():
    other_output.append(value[1])
print(other_output)

list_comprehension = [value[1] for value in racoona_valence.values()]
print(list_comprehension)

n = len(racoona_valence.values())-1
counter = 0
gene_list = []
while counter<=n:
    gene_list.append(list(racoona_valence.values())[n][1])
    counter += 1
print(gene_list)