简体   繁体   English

如何组合两个列表并将结果存储在字典中(在 Python 中)?

[英]How to combine two lists and store the result in a dictionary (in Python)?

I am trying to combine two lists and place them into a dictionary.我正在尝试组合两个列表并将它们放入字典中。 Here is my current code:这是我当前的代码:

    from string import*

    book_ratings=open("ratings.txt","r")
    usernames=[]
    ratings=[]
    for i in book_ratings.readlines(): #i=index
        i=split(i) #splits usernames from ratings
        rating=i[:] #allows whole ratings list to be stored in ratings 
        ratings.append(rating) #appends rating to ratings list
        usernames.append(i) #appends usernames to usernames list

    books=open("books.txt","r")
    book_list=[]
    i=books.readlines()
    book_list.append(i) #appends books to book_list list

    user_book_ratings={}
    for ratings in book_ratings:
        user_book_ratings.join(book_list,ratings)

Unfortunately, the last three lines only print out an empty list.不幸的是,最后三行只打印出一个空列表。 How do I combine the ratings and book_list lists, and place them in a dictionary with usernames as keys and the new list as values?如何组合 ratings 和 book_list 列表,并将它们放入字典中,以用户名作为键,将新列表作为值?

Thank you in advance.先感谢您。

*edit *编辑

The file ratings.txt appears as follows:文件ratings.txt如下所示:

"Ben 5 0 0 0 0 0 0 1 0 1 -3 5 0 0 0 5 5 0 0 0 0 5 0 0 0 0 0 0 0 0 1 3 0 1 0 -5 0 0 5 5 0 5 5 5 0 5 5 0 0 0 5 5 5 5 -5 Moose 5 5 0 0 0 0 3 0 0 1 0 5 3 0 5 0 3 3 5 0 0 0 0 0 5 0 0 0 0 0 3 5 0 0 0 0 0 5 -3 0 0 0 5 0 0 0 0 0 0 5 5 0 3 0 0..." (There are more users, these are the first two) "本 5 0 0 0 0 0 0 1 0 1 -3 5 0 0 0 5 5 0 0 0 0 5 0 0 0 0 0 0 0 0 1 3 0 1 0 -5 0 0 5 5 0 5 5 5 0 5 5 0 0 0 5 5 5 5 -5 驼鹿 5 5 0 0 0 0 3 0 0 1 0 5 3 0 5 0 3 3 5 0 0 0 0 0 5 0 0 0 0 0 3 5 0 0 0 0 0 5 - 3 0 0 0 5 0 0 0 0 0 0 5 5 0 3 0 0...”(用户较多,这是前两个)

When printed with the above code, appears as:当用上面的代码打印时,显示为:

"[['Ben'], ['5', '0', '0', '0', '0', '0', '0', '1', '0', '1', '-3', '5', '0', '0', '0', '5', '5', '0', '0', '0', '0', '5', '0', '0', '0', '0', '0', '0', '0', '0', '1', '3', '0', '1', '0', '-5', '0', '0', '5', '5', '0', '5', '5', '5', '0', '5', '5', '0', '0', '0', '5', '5', '5', '5', '-5'], ['Moose'], ['5', '5', '0', '0', '0', '0', '3', '0', '0', '1', '0', '5', '3', '0', '5', '0', '3', '3', '5', '0', '0', '0', '0', '0', '5', '0', '0', '0', '0', '0', '3', '5', '0', '0', '0', '0', '0', '5', '-3', '0', '0', '0', '5', '0', '0', '0', '0', '0', '0', '5', '5', '0', '3', '0', '0']..." "[['Ben'], ['5', '0', '0', '0', '0', '0', '0', '1', '0', '1', ' -3', '5', '0', '0', '0', '5', '5', '0', '0', '0', '0', '5', '0' ', '0', '0', '0', '0', '0', '0', '0', '1', '3', '0', '1', '0', '-5', '0', '0', '5', '5', '0', '5', '5', '5', '0', '5', '5', ' 0', '0', '0', '5', '5', '5', '5', '-5'], ['麋'], ['5', '5', '0 ', '0', '0', '0', '3', '0', '0', '1', '0', '5', '3', '0', '5', '0', '3', '3', '5', '0', '0', '0', '0', '0', '5', '0', '0', '0' ', '0', '0', '3', '5', '0', '0', '0', '0', '0', '5', '-3', '0' , '0', '0', '5', '0', '0', '0', '0', '0', '0', '5', '5', '0', ' 3', '0', '0']..."

The file books.txt appears as follows:文件books.txt显示如下:

Douglas Adams,The Hitchhiker's Guide To The Galaxy道格拉斯·亚当斯,银河系漫游指南

Richard Adams,Watership Down理查德·亚当斯,Watership Down

Mitch Albom,The Five People You Meet in Heaven米奇·阿尔博姆,你在天堂遇见的五个人

Laurie Halse Anderson,Speak劳里·哈尔斯·安德森,说

Maya Angelou,I Know Why the Caged Bird Sings玛雅·安吉洛,我知道笼中鸟为何歌唱

... (There are more books; these are the first five) ...(还有更多的书;这些是前五本)

When printed with the above code, looks like:当用上面的代码打印时,看起来像:

"[["Douglas Adams,The Hitchhiker's Guide To The Galaxy\\n", 'Richard Adams,Watership Down\\n', 'Mitch Albom,The Five People You Meet in Heaven\\n', 'Laurie Halse Anderson,Speak\\n', 'Maya Angelou,I Know Why the Caged Bird Sings\\n'..." "[["道格拉斯·亚当斯,银河系漫游指南\\n",'理查德·亚当斯,下水道\\n','米奇·阿尔博姆,你在天堂遇到的五个人\\n','劳里·哈尔斯·安德森,说\\n ', 'Maya Angelou,我知道笼中鸟为何歌唱\\n'..."

Ultimately, the dictionary should appear as:最终,字典应显示为:

{Ben:["Douglas Adams,The Hitchhiker's Guide to The Galaxy","5"],["Richard Adams,Watership Down","0"]... Moose:["Douglas Adams, The Hitchhiker's Guide to the Galaxy","5"]...} and so on (or something similar to that). {本:[“道格拉斯·亚当斯,银河系漫游指南”,“5”],[“理查德·亚当斯,Watership Down”,“0”]...穆斯:[“道格拉斯·亚当斯,银河系漫游指南” ","5"]...} 等等(或类似的东西)。

The idea is that each book is assigned a rating by the user in question.这个想法是每本书都由相关用户分配一个评级。

I hope I've made things clearer.我希望我已经把事情说清楚了。

Here is how to combine two lists:以下是组合两个列表的方法:

def combine(listone, listtwo):
    out = {}
    for k in range(0, len(listone)):
        out[listone[k]] = listtwo[k]
    return out

This runs as:这运行为:

>>> combine(['hello', 'is', 'a', 'word'], [5, 2, 1, 4])
{'a': 1, 'is': 2, 'word': 4, 'hello': 5}

By the way, those lists were basically getting the length of each string顺便说一句,这些列表基本上是获取每个字符串的长度

Get your booknames first , because you want to know those as you read the usernames - then you can put all the data straight into the final dict, with fewer intermediate lists.首先让你的booknames,因为你想知道那些当你阅读的用户名-那么你可以把所有的数据直入决赛字典,用较少的中间列表。 There's no need for any appending with this, since readlines already gives you a list - so, just do:不需要任何附加,因为readlines已经为您提供了一个列表 - 所以,只需:

with open('books.txt', 'r') as books:
    book_titles = books.readlines()

using the with statement ensures that the file will be closed as soon as you're done reading from it.使用 with 语句可确保在您完成读取文件后立即关闭该文件。

Now that you have that, the way you get the usernames and ratings is basically the same as what you have, although it can be simplified a little:有了这些,您获取用户名和评分的方式与您拥有的方式基本相同,尽管可以稍微简化一下:

with open('ratings.txt', 'r') as ratings:
   for line in ratings:
      username, *ratings = line.split()

This syntax tells Python to split the string and assign the first (left-most) component to username (as a string), and group the rest into a list and put in ratings.此语法告诉 Python 拆分字符串并将第一个(最左侧)组件分配给用户名(作为字符串),并将其余部分分组到一个列表中并放入评级。

The dictionary you want (you'll need to initialise it to an empty dict sometime before this loop) has the username as the key, and the value as a list of corresponding pairs from ratings and book_titles.您想要的字典(您需要在此循环之前的某个时间将其初始化为空字典)以用户名作为键,并将值作为来自 ratings 和 book_titles 的对应对的列表。 Python has a builtin called zip that gets those pairs for you - although it doesn't give you a list of pairs in Python 3, so you need to pass the result through list : Python 有一个名为zip的内置函数,可以为您获取这些对 - 尽管它在 Python 3 中没有给您一个对的列表,因此您需要通过list传递结果:

ratings_dict = {}
with open('ratings.txt', 'r') as ratings:
   for line in ratings:
      username, *ratings = line.split()
      ratings_dict[username] = list(zip(book_titles, ratings))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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