如何在列表列表中查找值的频率,并通过公共值与另一个现有列表组合?



我有一个由用户输入组成的音乐艺术家的嵌套列表,假设:

artists_list = [['A', 'B', 'C'],
['A', 'C', 'B'],
['B', 'A', 'D']]

我还设法创建了一个单独的列表,基于输入顺序(不是按字母顺序(,为上述列表中的每个独特艺术家分配一个流派:

artist_genre_list = [['A', 'Rock'],
['B', 'Rap'],
['C', 'Rock'],
['D', 'Blues']]

如何将这两者结合起来,使主列表或字典包含类似于以下频率计数:

master_list = [['A', 'Rock', 3],
['B', 'Rap', 3],
['C', 'Rock', 2],
['D', 'Blues', 1]]
master_dict = {'A': {
'Genre': 'Rock',
'Frequency': 3},
'B': {
'Genre': 'Rap',
'Frequency': 3},
'C': {
'Genre': 'Rock',
'Frequency': 2},
'D': {
'Genre': 'Blues',
'Frequency': 1}
}

顺序不一定是按字母顺序排列的。以下是我为创建前两个列表所做的示例:

# Counters
count = 1
new_artist_counter = 0
# Generate Lists
artists_input_list = []
aux_artists_list = []
aux_genre_list = []
aux_artists_genre_list = []
def merge(aux_artists_list, aux_genre_list):
merged_list = [[aux_artists_list[i], aux_genre_list[i]] for i in range(0, 
len(aux_artists_list))]
return merged_list
while count < 4:
# Inputs
a1_in = str(input("Artist 1: "))
a2_in = str(input("Artist 2: "))
a3_in = str(input("Artist 3: "))
artists_input_list.append([a1_in, a2_in, a3_in])
# Determines if new unique artist has been added and asks for it's genre
while new_artist_counter < len(artists_input_list):
for entry in artists_input_list:
for artist in entry:
if artist not in aux_artists_list:
aux_artists_list.append(artist)
genre_input = input("What is "+artist+"'s genre? ")
aux_genre_list.append(genre_input)
else: continue
new_artist_counter += 1  
aux_artists_genre_list = merge(aux_artists_list, aux_genre_list)
# Counter updates
count += 1
print(artists_input_list)
print(aux_artists_genre_list)

这就是我想出的。它首先扁平化您的艺术家列表,获取列表中每个项目的频率,然后将其与您的genre列表组合在一起

from itertools import groupby, chain
import pprint
artists_list = [
['A', 'B', 'C'],
['A', 'C', 'B'],
['B', 'A', 'D']
]
artist_genre_list = [
['A', 'Rock'],
['B', 'Rap'],
['C', 'Rock'],
['D', 'Blues']
]
frequencies = {
key: len(list(value)) for key,
value in groupby(sorted(chain.from_iterable(artists_list)))
}
frequency = [{
letter: {
'Genre': genre,
'Frequency': next((freq
for key, freq in frequencies.items() if key is letter), 0)
}
}
for letter, genre in artist_genre_list
]
pprint.pprint(frequency)

我使用pprint只是为了让输出更整洁,显示为

[{'A': {'Frequency': 3, 'Genre': 'Rock'}},
{'B': {'Frequency': 3, 'Genre': 'Rap'}},
{'C': {'Frequency': 2, 'Genre': 'Rock'}},
{'D': {'Frequency': 1, 'Genre': 'Blues'}}]

相关内容

  • 没有找到相关文章

最新更新