在python中循环并行列表(Looping over parallel lists in python)

编程入门 行业动态 更新时间:2024-10-24 14:20:36
在python中循环并行列表(Looping over parallel lists in python)

我正在阅读itunes库文件。 我抓住了艺术家的名字和歌曲,并将它们放在平行列表中,其中一个包含艺术家名字,另一个包含艺术家歌曲。 我想通过仅使用列表来做到这一点

artist_choice = input("Enter artist name: ") artist_names = [Logic, Kanye West, Lowkey, Logic, Logic] artist_songs = [Underpressure, Stronger, Soundtrack to the struggle, Ballin, Im the man]

假设用户输入艺术家名称Logic,我将如何循环并行列表并打印出与艺术家Logic相关的每首歌曲? 如果用户输入Logic,则输出应为:

Underpressure Ballin Im the man

Im reading over an itunes library file. I scraped the artist names and songs and put them in parallel lists, one containing artist names and another containing artist songs. I would like to do this by using only lists

artist_choice = input("Enter artist name: ") artist_names = [Logic, Kanye West, Lowkey, Logic, Logic] artist_songs = [Underpressure, Stronger, Soundtrack to the struggle, Ballin, Im the man]

Say the user inputs the artist name Logic, how would i loop through the parallel list and print out every song associated with the artist Logic? if the user entered Logic the output should be:

Underpressure Ballin Im the man

最满意答案

这是sudo代码,如何做到这一点,我实际上不太了解python。

results = []; for (i=0;i<artist_names.length();i++): 1 if artist_names[i] == artist_choice: results.push(artist_songs[i])

但正如@Carcigenicate所说,有更好的方法来解决这个问题。 如果您要在这些列表上进行多次搜索,您可能需要首先循环并将数据分组到哈希表或@Carcigenicate建议的内容中。

@RPGillespie的链接解释了如何将它们组合成哈希表,这是一种更好的搜索方式。

This is sudo code for how to do it, I actually don't know much python.

results = []; for (i=0;i<artist_names.length();i++): 1 if artist_names[i] == artist_choice: results.push(artist_songs[i])

but as @Carcigenicate said, there are better ways of going about this. If you are going to be making many searches on these lists you may want to first loop through and group the data into a hash table or what @Carcigenicate suggests.

@RPGillespie 's link explains how to combine them into a hash table, this is a much better way of searching.

更多推荐

本文发布于:2023-07-30 00:07:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1320839.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:列表   python   Looping   lists   parallel

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!