【问题标题】:How can I add element of a list in loop elegantly?如何优雅地在循环中添加列表元素?
【发布时间】:2019-10-31 03:50:13
【问题描述】:

这是一个简单的问题。这是一个例子:

数据:

score = [10, 20]
weight = [0.2, 0.8]

这是我的代码:

score = [10, 20]
weight = [0.2, 0.8]
score_list = []
for i, k1 in enumerate(score):
    k_score = 100 if k1 < 20 else 95
    k_score *= weight[i]
    score_list.append(k_score)
sum_score = sum(score_list)

使用上面的代码我可以得到我想要的,但是我觉得它不优雅,我想调整一下,你能给一些建议吗?

【问题讨论】:

  • for w, k in zip(weight, score): 是枚举的替代品。

标签: python python-3.x pandas list numpy


【解决方案1】:

您可以只取一个运行总和,而不是将每个单独的值存储在score_list

score = [10, 20]
weight = [0.2, 0.8]
sum_score = 0

for i, k1 in enumerate(score):
    k_score = 100 if k1 < 20 else 95
    k_score *= weight[i]
    sum_score += k_score

print(sum_score)

【讨论】:

  • 很好,还有什么可以改进的吗?
【解决方案2】:

好吧,如果你正在尝试 numpy,你基本上可以得到 dot product

score = np.array(score)
output = np.dot(np.where(score<20,100,95),weights)

print(output)
96

【讨论】:

    【解决方案3】:

    试试下面的代码,希望对你有帮助:

    sum([100*wei if sco < 20 else 95*wei for sco,wei in zip(score,weight)])
    

    输出:

    96.0
    

    【讨论】:

      猜你喜欢
      • 2015-12-05
      • 1970-01-01
      • 2016-08-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-10-09
      • 2019-11-05
      相关资源
      最近更新 更多