简体   繁体   English

将txt文件导入字典中的元组

[英]importing txt file into tuple within dictionary

I have a data structure in a .txt file set up as follows: 我在.txt文件中设置了数据结构,如下所示:

andrew
3 3 1 0 3 0 3 0 0 -3 0 5 3 0 1 0 0 5 3 0 0 0 0 1 0 3 0 1 0 0 3 5 3 3 0 
0 0 5 0 5 0 3 3 0 -3 0 0 5 1 5 3 0 3 0 0 

I'm trying to import it as in this format: 我正在尝试以这种格式导入它:

{'user':[0,1,3,4,5]}

I've tried various implementations, but can't find anything to suit my needs and account for so many variables. 我已经尝试了各种实现,但是找不到任何适合我的需求并说明了这么多变量的东西。

My current code is as follows: 我当前的代码如下:

    with open('ratings.txt', 'r') as f:
    for line in f:
        x = line.split()
        print(x)
        ratings[x[0]] = [y for y in x[1:]])

Any idea on how to improve the code, please? 对如何改进代码有任何想法吗?

you can read the whole file by read() method then split it so that you can create the dict as you want with out reading line by line 您可以通过read()方法读取整个文件,然后将其拆分,以便可以创建所需的字典,而无需一行一行地读取

ratings = {}
with open('ratings.txt', 'r') as f:
    X = f.read().split()

    x = set([int (i) for i in X[1:] if int(i) >= 0]) # this will create a set which values are >= 0

    ratings[X[0]] = list(x) 


print(ratings)# output --> {'andrew': [0, 1, 3, 5]}

this is assuming your text file will always be in the format you mention above only one user at a time 假设您的文本文件将始终采用您上面提到的格式,一次仅一个用户

As per Your text File I think you can do like this : you read 2 lines by 2 to until you find a empty line or the end of file like below 根据您的文本文件,我认为您可以这样做:您将2行乘2读到直到找到空行或文件末尾,如下所示

ratings = {}
with open('ratings.txt', 'r') as f:
    while True:
        name = f.readline().strip()
        values = f.readline().strip().split()
        #print(values)
        if not name: break
        else:
            ratings[name] = list(set(int (i) for i in values if int(i) >= 0))

print(ratings)# output --> {'andrew': [0, 1, 3, 5]}

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

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