【问题标题】:Passing dictionary with other values formatted between functions传递字典与函数之间格式化的其他值
【发布时间】:2013-12-14 08:45:01
【问题描述】:

我想传递整个字典的键,在循环中调用的另外 2 个值因此将被组合并逐行打印。值被传递给另一个函数,但只有整个字典的第一个值被传递。我希望所有值与其他变量一起传递,如下所示。我会怎么做才能让所有值都被传递,而不仅仅是一个。

这是我的代码:

class scoring:

   def values(self):
      dicts = {}
      inner_dict = {}
      with open("1.txt","r") as f:
         for line, score in zip(sys.stdin, f):
            d2  = ast.literal_eval(score)
            for key,v in d2.items():
               inner_dict = dicts.setdefault(key, {})
               inner_dict['s'] = v.get('s')
               sent = dicts[key]['s']
               binary = re.split("\s+", line.strip())[0]
               return key, sent, binary

   def score(self,key,sent,binary):
      <something>

if __name__ == "__main__":

   call = scoring()
   key,sent,binary = call.values()
   call.score(key,sent,binary)

【问题讨论】:

    标签: python file list file-io dictionary


    【解决方案1】:

    我没有在 python 中进行真正的编码,但我猜你是从内部循环的第一次迭代中返回的,可能这就是为什么其他值永远不会返回的原因。您可以保存所有值列表,然后可以返回列表并访问列表中的值。

    class scoring:
    
       def values(self):
          dicts = {}
          list = []
          inner_dict = {}
          with open("1.txt","r") as f:
             for line, score in zip(sys.stdin, f):
                d2  = ast.literal_eval(score)
                for key,v in d2.items():
                   inner_dict = dicts.setdefault(key, {})
                   inner_dict['s'] = v.get('s')
                   sent = dicts[key]['s']
                   binary = re.split("\s+", line.strip())[0]
                   list.append((key, sent, binary))
          return key, sent, binary
    
       def score(self,key,sent,binary):
          <something>
    
    if __name__ == "__main__":
    
       call = scoring()
       lst = call.values()
       for l in lst :
            call.score(l[0],l[1],l[2])
    

    基本思想是做这样的事情:

    lst = []
    lst.append((1,2,3))
    lst.append((4,5,6))
    for l in lst :
       print l[0], l[1], l[2]
    

    它会打印出来

    1 2 3
    4 5 6
    

    【讨论】:

    • 我收到一个错误:TypeError: 'int' object has no attribute 'getitem' on this line call.score(l[0],l[1],l [2])
    【解决方案2】:

    您的 return 语句位于两个 for 循环内。这意味着在return 语句离开函数之前,您只需要执行一次循环。这是我可以在没有更多信息的情况下提供的尽可能多的帮助,因为您可能想使用yield 或创建列表或定义可以被整个类引用的类属性。 Phase 提供更详细的所需输出。

    【讨论】:

      猜你喜欢
      • 2012-12-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-03-08
      • 1970-01-01
      • 1970-01-01
      • 2019-12-12
      相关资源
      最近更新 更多