【问题标题】:Confused with Chemical Formula Function Design : If statement won't print "Hi" when it's supposed to对化学式函数设计感到困惑:如果语句在应该打印时不会打印“Hi”
【发布时间】:2019-07-28 10:53:42
【问题描述】:
def compound_properties(csv_name, compound_formula):
compDict = molform(compound_formula)

compK = compDict.keys()
sList = []
ele = ''
with open("atoms.csv", "r") as atomsF:
elemData = list([row for row in csv.reader(atomsF)])
for i in compK:
  ele = str(i)
  for j in elemData: 
    sList = j
    if ele in sList:
      print('hi')

如何检查此元素是否在我使用 for 循环生成的列表中?我拥有的 If 语句没有像预期的那样打印“hi”。我该如何解决??

此函数有两个参数:csv 文件名和化合物的公式。

它应该调用 molform() 函数来获取分子的组成和 从 csv 文件中获取所需的属性。 csv 文件将包含所有 所需的属性。

这个函数需要返回一个包含三个属性的元组: 1. 沸点最低的原子的名称。 例如,如果是氧气,则返回 'Oxygen',而不是 'O'

【问题讨论】:

  • 你可以试试sList = j,而不是sList.append(j)。并尝试再次运行代码。
  • 如果您向我们提供更多信息(compDict 的外观、函数应该返回的其他内容、csv_name 的作用等),我们可以为您提供更好的帮助。

标签: python list loops csv dictionary


【解决方案1】:

首先,您可以通过删除不必要的声明来大大缩短您的代码。

编辑:我猜你想打开csv_name,而不是"atoms.csv"

删除所有过时的内容后,它看起来像这样(查看here 以获取有关csv.reader 的更多信息):

def compound_properties(csv_name, compound_formula):
    compDict = molform(compound_formula)

    with open(csv_name, "r") as atomsF:
        elemData = csv.reader(atomsF) # csv.reader already returns a list of rows

    for i in compDict:  # for loop automaticaly iterates over dict keys
        for j in elemData:
            if str(i) in j:  # no need to assign i or j to additional variables
                print('hi')

没有任何真实的示例数据,我现在不能说更多,因为问题不在这个 for 循环中。有了测试数据,就完美运行了:

elem_data = [['this', 'is', 'the', 'first', 'row'], ['this', 'is', 'the', 'bar', 'row'], ['this', 'is', 'all', 'a', 'big', 'foo']]

compDict = {'foo': 1, 'bar': 2, 'baz': 3}

for i in compDict:
    for j in elemData:
        if str(i) in j:
            print('{} was found in line {}'.format(i, elemData.index(j) + 1))

输出:

foo was found in line 3
bar was found in line 2

【讨论】:

  • 当心,永远不要迭代文件(或 csv.reader') inside a loop! You will reach the end of file after first iteration and the following ones will process an empty file... You must use the opposite order: for j in elemData: for i in compDict: ...`
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-01-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-08-15
相关资源
最近更新 更多