与化学式函数设计混淆:If语句在假设时不打印“Hi”

2024-10-04 11:25:00 发布

您现在位置:Python中文网/ 问答频道 /正文

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”


Tags: csv函数infor属性rowformulaslist
1条回答
网友
1楼 · 发布于 2024-10-04 11:25:00

首先,通过删除不必要的声明,可以大大缩短代码。你知道吗

编辑:我猜您想打开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

相关问题 更多 >