【问题标题】:Calling items from lists within a function in python 3从python 3中的函数内的列表中调用项目
【发布时间】:2021-04-13 21:04:30
【问题描述】:

我正在尝试创建一个函数来调用函数之外的 2 个列表中的项目,但我很困惑,不知道去哪里或如何去做。问题是:编写一个算法,该算法将调用一个函数来确定由以下每个元素 [“H”、“Li”、“Na”、“K”] 形成的氯化物的公式权重,其权重分别为 [1.01, 6.94 , 22.99, 39.10]。 到目前为止,我已经编写了这个代码:

elementsList = ["H", "Li", "Na", "K"]

weightsList = [1.01, 6.94, 22.99, 39.10]

chlorine = "Cl"

weight = 35.45

def formulaWeight ():

   element = elements[]

请帮忙看看怎么做,我真的很难过

【问题讨论】:

  • 对于我们这些化学知识有限的人,您能给出一些示例输入和输出吗?
  • 什么是elements,应该是elementsList?
  • 是的,抱歉,我正在编辑,没听懂

标签: python list algorithm function


【解决方案1】:

您可以使用zip() 循环遍历每个元素及其相关权重,然后将其添加到氯权重中:

elementsList = ["H", "Li", "Na", "K"]

weightsList = [1.01, 6.94, 22.99, 39.10]

chlorine = "Cl"

chlorineWeight = 35.45

def formulaWeight():
    for element, weight in zip(elementsList, weightsList):
        chlorideWeight = weight + chlorineWeight
        print(f"{element}{chlorine} has weight {chlorideWeight}")

【讨论】:

  • 哦,好吧!那讲得通!谢谢
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2015-05-01
  • 2017-04-22
  • 2023-03-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多