【问题标题】:How can I store this in a dictionary?如何将其存储在字典中?
【发布时间】:2019-04-14 09:55:01
【问题描述】:

我必须写一本字典。这是我第一次这样做,我无法绕过它。前 5 个元素应该是它的键,其余的是值。

for i in verseny:
    if i not in eredmeny:
        eredmeny[i] = 1

    else:
        eredmeny[i] += 1

YS869 CCCADCADBCBCCB 这是来自硬件的一行。这个YS869 应该是键,这个CCCADCADBCBCCB 应该是值。

问题是我无法将它们存储在字典中。我在这里磨齿轮,但一无所获。

【问题讨论】:

  • 有什么问题?
  • 我无法将它们存储在字典中。我不知道怎么做:/
  • 你能分享你的完整代码吗?我不知道 sn-p 中发生了什么。
  • 这是一堆其他任务,但我可以。
  • ``` beolv = open("C:\\Users\\karol\\Documents\infoshit\\e_inffor_17maj\\Forrasok\\4_Tesztverseny\\valaszok.txt","r") verseny = beolv.readlines() print("A fájl sikeresen be lett olvasva és tárolva") seged1 = 0 for i in range(len(verseny)-1): seged1 += 1 print("A vetélkedőn" + " " + str (seged1)+ " " + "vett részt") eredmeny = {} azonkeres = input("Kérem adja meg a keresett azonosítót:") for i in verseny: if i not in eredmeny: eredmeny[i] = 1 else: eredmeny [i] += 1 for j,k in eredmeny.items(): print(str(k)) ```

标签: python dictionary


【解决方案1】:

假设 erdemeny 是您的字典名称,而 verseny 是包含您的值和键字符串的列表。应该这样做:

verseny = ['YS869 CCCADCADBCBCCB', 'CS769 CCCADCADBCBCCB', 'BS869 CCCADCADBCBCCB']
eredmeny = {}

for i in verseny:
    key, value = i.split(' ')[0], i.split(' ')[1]
    if key not in eredmeny.keys():
        eredmeny[key] = value
    else:
        eredmeny[key].append(value)

【讨论】:

  • 非常感谢。严重地!非常感谢您和 @alec_a 的帮助!
【解决方案2】:

我不是很了解这个问题,但完成手头任务的一种简单方法是将列表转换为字符串,然后使用split()

line = 'YS869 CCCADCADBCBCCB'
words = l.split()
d = {ls[0]: ls[1]}

print(d)

【讨论】:

    【解决方案3】:

    这是python的基本功。我希望你能参考现有的材料。作为您的示例,给出了以下演示:

    line = 'YS869 CCCADCADBCBCCB'
    dictionary = {}
    dictionary[line[:4]] = line[5:]
    
    print(dictionary)  # {'YS86': ' CCCADCADBCBCCB'}
    

    【讨论】:

      猜你喜欢
      • 2015-05-09
      • 2020-01-26
      • 2013-09-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-07-07
      • 1970-01-01
      相关资源
      最近更新 更多