【问题标题】:Loop over three lists simultaneously: nested loop not working同时循环三个列表:嵌套循环不起作用
【发布时间】:2017-08-17 20:45:31
【问题描述】:

我目前正在尝试同时循环三个列表:

list_weight = [0.9,0.3,0.6,0.4]
list_reliability = [0.8,0.5,0.2,0.8]
belief_CRED0 = [create_belief_matrix ('ACBA').iloc[0]] 

belief_CRED0
Out[40]: 
[1    0.562500
 2    0.562500
 3    0.391304
 4    0.391304
 Name: CRED0, dtype: float64]

首先我创建了一个嵌套循环:

for belief in belief_CRED0:
    for weight in list_weight:
        for reliability in list_reliability:
            m = [(1/(1+weight-reliability))*(weight*belief)]
print(m)

但结果完全关闭。所以我尝试这样做:

for belief, weight, reliability in zip(belief_CRED0, list_weight, list_reliability):
    m = [(1/(1+weight-reliability))*(weight*belief)]
print(m)

但结果也是错误的:

m
Out[42]: 
[1    0.460227
 2    0.460227
 3    0.320158
 4    0.320158
 Name: CRED0, dtype: float64]

从结果来看,循环似乎只使用了相应列表中的第一个权重和可靠性(权重 = 0.9 和可靠性 = 0.8)。

正确的输出应该是:

[1    0.460227
 2    0.210937
 3    0.16770171
 4    0.26086933

我该怎么办?

【问题讨论】:

  • 在不知道 [create_belief_matrix ('ACBA').iloc[0]] 在做什么的情况下很难回答这个问题。
  • 您的输出将永远是最后一个m 集。正确答案可能在循环的不同部分。
  • zip 的 for 循环中有一个错误 ...您说 m = [...] ...您应该将 m 作为一个空列表开始...和m.append((1/ ...))。那个嵌套循环是完全错误的。
  • 你的变量 m 被重写每个内部循环。如果你总是使用等长的数组,那么你应该只使用一个索引,即:for i in range(4):

标签: python loops for-loop nested-loops


【解决方案1】:

zip 上的 for 循环中的小错误(顺便说一句,这是最好的方法)。累积结果...而不是一直分配给m

m = []
for belief, weight, reliability in zip(belief_CRED0, list_weight, list_reliability):
    m.append(weight*belief/(1+weight-reliability))
print(m)

【讨论】:

  • 感谢您提供此解决方案!我没想过从一个空列表开始工作。
【解决方案2】:

如果他们都是pandas.Seriesnumpy.array 那么你可以直接这样做,例如:

>>> weight = pd.Series(list_weight, index=range(1, 5))
>>> reliability = pd.Series(list_reliability, index=range(1, 5))
>>> 1/(1+weight-reliability)*(weight*belief_CRED0)
1    0.460227
2    0.210937
3    0.167702
4    0.260869
dtype: float64

numpy类似:

>>> weight = np.array(list_weight)
>>> reliability = np.array(list_reliability)
>>> 1/(1+weight-reliability)*(weight*belief_CRED0)
1    0.460227
2    0.210937
3    0.167702
4    0.260869
Name: CRED0, dtype: float64

【讨论】:

  • 这真的很高效!我现在要更改我的代码以使用数组。谢谢!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-04-22
  • 2016-04-02
  • 2017-06-01
相关资源
最近更新 更多