【问题标题】:assign list values to dictionary python将列表值分配给字典python
【发布时间】:2021-12-27 12:52:42
【问题描述】:

所以我正在使用一组由

组成的字典
{'Summery':["00","01","02"],'Location':["03","04"],'Name':["05"]}

现在每个数字都与每行的字数相关

在我拥有的文本文件中,格式如下的行

Fun Reading Afterschool 50°N 50°E Library
Education Learning Study 51°N 51°E School
Exercise Play Social 52°N 52°E Playground

如何将 input.txt 转换为所需的输出:

输出.txt

{'Summery':["Fun","Reading","Aftershchool"],'Location':["50°N","50°E"],'Name':["Library"]}
{'Summery':["Education","Learning","Study"],'Location':["51°N","51°E"],'Name':["School"]}
{'Summery':["Exercise","Play","Social"],'Location':["52°N","52°E"],'Name':["Playground"]}

目前为止

file = open("input.txt", 'r')
lines = file.readlines()

list_word = []
for l in lines:
    list_word.append(l.split(" "))

my_list = [line.split(' , ')for line in open ("test")]

string1="".join(map(str,my_list))
print(string1)

new_main = open("output.txt", 'w')
new_main.write(string1)
new_main.close()

打印并创建 output.txt

['Fun Reading Afterschool 50°N 50°E Library\n']['Education Learning Study 51°N 51°E School\n']['Exercise Play Social 52°N 52°E Playground']

【问题讨论】:

  • 键是否需要使用单引号,或者你可以使用双引号,在这种情况下你可以使用json.dumps来生成有效的JSON?
  • 引号,没关系。我将如何添加 json.dump 以使其正常工作?

标签: python loops replace


【解决方案1】:

假设摘要总是 3 个单词,位置 2 和名称 1 个单词(每个单词由一个空格分隔),您可以根据它们的索引获取想要的单词。

for string in string1:
    splits = string.split(" ")
    
    summary = splits[0:3]
    location = splits[3:5]
    name = splits[5:6]
    
    print(f"Summary: {summary}, location: {location}, name: {name}")

【讨论】:

  • 我还没有设法让它打印出所需的输出。 (对不起,python 新手)
  • 我得到的错误如下 splits = string.split(" ") AttributeError: 'list' object has no attribute 'split'
  • 这是因为您的字符串作为列表存储在“string1”数组中。尝试做 string = string[0]。最好的解决方案是不要将它们保留为列表,但让我们坚持这一点,因为您是新手 :)
  • 现在它只是将列表分解成单个字符并将它们输入到summery中。摘要:['['],位置:[],名称:[] 摘要:[“'”],位置:[],名称:[] 摘要:['F'],位置:[],名称:[ ] 摘要:['u'],位置:[],名称:[] 摘要:['n'],位置:[],名称:[]
  • 知道了 - 对于 string1 中的字符串:: string = string[0] splits = string.split(" ") 谢谢
猜你喜欢
  • 2021-04-02
  • 2018-08-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-01-23
  • 2021-12-10
相关资源
最近更新 更多