我会尽力解释我的情况。
我有一个包含名称的列表
name_list = ["Bob" , "Henry" , "Jeff" , "Harry"]
和另一个包含数字的列表
number_list = ["1,4,2,3" , "4,3,1,2" , "3,2,4,1" , "1,2,3,4" , "4,3,2,1" , "1,2,4,3"]
我正在努力想出一个代码,它将创建一个将每个名称与name_list中相应位置相关联的记录
即
"result" = Bob - 1:3 , 2:0 , 3:1 , 4:2
Henry- 1:0 , 2:3 , 3:2 , 4:1
Jeff - 1:1 , 2:2 , 3:1 , 4:2
Harry- 1:2 , 2:1 , 3:2 , 4:1
这实际上是否可以实现?因为我觉得我现在已经死了一段时间,我拼命地需要帮助。我对此代码的思考过程是计算出现的每个数字的出现次数,然后(因为此代码用于即时径流投票系统)确定谁具有最高的1个计数,依此类推。
这是即时决选投票代码的一部分,关于我是否在正确的轨道上的任何信息都是非常可取的
答案 0 :(得分:0)
你可以试试这个:
name_list = ["Bob" , "Henry" , "Jeff" , "Harry"]
number_list = ["1,4,2,3" , "4,3,1,2" , "3,2,4,1" , "1,2,3,4" , "4,3,2,1" , "1,2,4,3"]
new_number_list = [list(map(int, i.split(","))) for i in number_list]
final_data = {a:{c:sum(d[i] == c for d in [e for e in new_number_list if e != a]) for c in new_number_list[i]} for i, a in enumerate(name_list)}
输出:
{'Bob': {1: 3, 2: 0, 3: 1, 4: 2}, 'Jeff': {1: 1, 2: 2, 3: 1, 4: 2}, 'Harry': {1: 2, 2: 1, 3: 2, 4: 1}, 'Henry': {1: 0, 2: 3, 3: 2, 4: 1}}
编辑:要保持所有值的排序,您可以使用:
new_final_data = {a:sorted(b.items(), key=lambda x:x[0]) for a, b in final_data.items()}
输出:
{'Henry': [(1, 0), (2, 3), (3, 2), (4, 1)], 'Bob': [(1, 3), (2, 0), (3, 1), (4, 2)], 'Harry': [(1, 2), (2, 1), (3, 2), (4, 1)], 'Jeff': [(1, 1), (2, 2), (3, 1), (4, 2)]}
答案 1 :(得分:0)
我是怎么做的,我不确定你是否需要一个功能,因为你没有指定
from collections import Counter
from itertools import chain
# first lets create a list of dictionaries mapping each name to a number
maps = [dict(zip(name_list, chunk.split(','))) for chunk in number_list]
[{'Bob': '1', 'Harry': '3', 'Henry': '4', 'Jeff': '2'},
{'Bob': '4', 'Harry': '2', 'Henry': '3', 'Jeff': '1'},
{'Bob': '3', 'Harry': '1', 'Henry': '2', 'Jeff': '4'},
{'Bob': '1', 'Harry': '4', 'Henry': '2', 'Jeff': '3'},
{'Bob': '4', 'Harry': '1', 'Henry': '3', 'Jeff': '2'},
{'Bob': '1', 'Harry': '3', 'Henry': '2', 'Jeff': '4'}]
for name in name_list:
temp = Counter()
# counter object where name is the key, value is another counter object
temp.update({name: Counter(map(lambda x: x.get(name), maps))})
num = len(temp.values()[0].keys())
# create string to format
fmt = '{} has {} occurences, ' * num
print '{} - '.format(name) + fmt.format(*list(chain.from_iterable(temp.values()[0].items())))
Bob - 1 has 3 occurences, 3 has 1 occurences, 4 has 2 occurences,
Henry - 3 has 2 occurences, 2 has 3 occurences, 4 has 1 occurences,
Jeff - 1 has 1 occurences, 3 has 1 occurences, 2 has 2 occurences, 4 has 2 occurences,
Harry - 1 has 2 occurences, 3 has 2 occurences, 2 has 1 occurences, 4 has 1 occurences,