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.沸点最低的原子名称。 例如,如果是氧气,则返回“氧气”,而不是“ O”
答案 0 :(得分:0)
首先,您可以通过删除不必要的声明来大大缩短代码。
编辑:我猜您要打开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