【问题标题】:How to loop through an array of lists, check an element within each list and compare to a value and if it matches the value return the key如何遍历列表数组,检查每个列表中的元素并与值进行比较,如果它与值匹配则返回键
【发布时间】:2019-06-28 10:57:22
【问题描述】:

我有一个包含数百个数组的数组,我正在尝试遍历每个数组并测试每个数组中的一个元素以查看它是否存在于字典中。如果是,则返回与值匹配的键。这是我卡住的地方。这就是我想要完成的任务。

dictionary = {'Bob' : '1', 'John' : '2', 'Andy': '3'}
list = [['5','2019','$50'],['1','2019','$50'],['5','2018','$50']

with open('C:/...','w',newline='') as f:
    fieldName = ['ID','Name','Price']
    writer = csv.DictWriter(f, fieldnames=fieldName)
    writer.writeheader()
    for i in list:
        if i[0] in dictionary.values():
            writer.writerow({'ID' : i[0], 'Name' : *DictionaryKey*, 'Price' : i[2]})

【问题讨论】:

  • 您当前的代码有什么问题?
  • 你不应该使用list作为变量名,因为它是python中的保留关键字
  • 另外,考虑使用'w+' 作为打开文件的模式,如果文件不存在,它将负责创建文件。
  • 循环内的if语句,通过每个循环检查每个列表中的第一个元素,如果它在字典值中,则返回键。所以第二个循环的输出应该是 ID: 1 Name: Bob
  • 如果可能的话,我会重组你的字典,所以 ID (1, 2, 3 ...) 是关键。

标签: python arrays list csv dictionary


【解决方案1】:

您通过从值中搜索键来错误地使用您的字典:它应该是相反的。另外,与该值对应的键可能不止一个。

你的代码应该在这个模板上:

dictionary = {'1': 'Bob', '2': 'John', '3': 'Andy'}
my_list = [['5','2019','$50'],['1','2019','$50'],['5','2018','$50'] # do not use 'list' as variable name

with open('C:/...','w+',newline='') as f:
    fieldNames = ['ID','Name','Price']  
    writer = csv.DictWriter(f, fieldnames=fieldNames)
    writer.writeheader()

    for id_, year, price in my_list:
        if id_ in dictionary.values():
            writer.writerow({'ID' : id_, 'Name' : dictionary[id_], 'Price' : price})

【讨论】:

    【解决方案2】:

    这是我的问题的解决方案:

    dictionary = {'1' : 'Bob', '2' : 'John', '2': 'Andy'}
    my_list = [['5','2019','$50'],['1','2019','$50'],['5','2018','$50']]
    
    with open('C:/...','w',newline='') as f:
    fieldName = ['ID','Name','Price']
    writer = csv.DictWriter(f, fieldnames=fieldName)
    writer.writeheader()
    for i in list:
      for key, value in dictionary:
          if i[0] == key:
               writer.writerow({'ID' : i[0], 'Name' : key, 'Price': i[2]})
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-03-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-10-30
      相关资源
      最近更新 更多