【问题标题】:Python: for loopPython:for循环
【发布时间】:2012-06-08 23:19:55
【问题描述】:

我正在尝试创建一个 for 循环来为已建立的键添加值 字典。但是,我不断得到最后一个值而不是所有 价值观。我做错了什么?

我当前的字典看起来像:

growth_dict = dict.fromkeys(conc[1:9], '')

growth_dict = {'100 ug/ml': '', '12.5 ug/ml': '', '50 ug/ml': '', 
    '0 ug/ml': '', '6.25 ug/ml': '', '25 ug/ml': '', '3.125 ug/ml': '', 
    '1.5625 ug/ml': ''}

cols_list = numpy.loadtxt(fn, skiprows=1, usecols=range(1,9), unpack=True)

numer = (0.301)*960 #numerator

for i in cols_list:

    N = i[-1]
    No = i[0]
    denom = (math.log(N/No)) #denominator
    g = numer/denom

当我运行程序并输入“growth_dict”时,它会返回我的字典,其中只有最后一个值作为键:

growth_dict = {'100 ug/ml': 131.78785283808514, '12.5 ug/ml': 131.78785283808514, 
    '50 ug/ml': 131.78785283808514, '0 ug/ml': 131.78785283808514, 
    '6.25 ug/ml': 131.78785283808514, '25 ug/ml': 131.78785283808514, 
    '3.125 ug/ml': 131.78785283808514, '1.5625 ug/ml': 131.78785283808514}

【问题讨论】:

  • 运行这个程序时你会得到什么输出?你期望的输出是什么?

标签: python loops for-loop


【解决方案1】:

每次执行此操作时,您都会覆盖 conc[j] 字典条目的值:

growth_dict[conc[j]] = g

如果您希望将每个连续的g 附加到字典条目,请尝试以下操作:

for j in conc:
    # The first time each key is tested, an empty list will be created
    if not instanceof(growth_dict[conc[j]], list):
        growth_dict[conc[j]] = []
    growth_dict[conc[j]].append(g)

【讨论】:

  • 但我认为字典没有属性“追加?”
  • @ttdinh:它是一个列表字典——每个列表都有 .append()
【解决方案2】:

您还可以通过这样做来节省大量加载数据的工作

cols_list = numpy.loadtxt(fn, skiprows=1, usecols=range(1,9), unpack=True)

【讨论】:

  • 谢谢!这是我的第一个编程课,所以我还在努力弄清楚这些东西
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-09-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多