我是编码新手。 Python是我的第一语言。我正在尝试制作一个程序,将电阻值从csv文件转换为相应的颜色代码。 这是csv文件的代码段:
4700 ohm, 5% = yellow violet red, gold
1000 ohm, 5% = brown black red, gold
150 ohm, 5% =
3300 ohm, 5% =
470 ohm, 2% =
3K3, 5% =
150 ohm, 1% =
10M, 10% =
我已经完成了工作代码,但是不得不修改以考虑所有其他格式(例如3K3、10M)。这是我根据输入做出的列表清单的一部分
print(type(data))
for i in data[:8]:
print(i)
输出:
PS C:\Users\User> & python c:/Users/User/resistor.py
<class 'list'>
['4700', '5']
['1000', '5']
['150', '5']
['3300', '5']
['470', '2']
['3K3', '5']
['150', '1']
['10M', '10']
我正在使用几个嵌套的循环,通过字典来尝试分配电阻的颜色。我很难知道代码出了什么问题。第一个通过字典循环有效,但出现第二个字典错误。
# Assign colors given the tolerances
tol_color = {
10 : 'silver' ,
5 : 'gold' ,
1 : 'brown' ,
2 : 'red' ,
0.5 : 'green' ,
0.25 : 'blue' ,
0.1 : 'violet' ,
20 : 'none' ,
}
Tolerance = []
for i in data:
x = float(i[1])
for key, value in tol_color.items():
if key == x:
Tolerance.append(value)
else:
Tolerance.append('unknown')
# Identify true ohmic values then store to Ohmic_Value
# Identify the significant digits
Ohmic_Value = []
significant = []
digitcode = {
'kilo' : 3 ,
'mega' : 6 ,
'R' : 0 ,
'K' : 3 ,
'M' : 6 ,
}
for i in data:
x = str(i[0])
for key, value in digitcode.items():
if value == 6 and key in x: # <------- this is line 60
x = x.replace(key,'.')
elif key in x:
x = x.replace(key,'.')
else:
pass
x = float(x)
x *= 10**value
Ohmic_Value.append(x)
significant.append(str(x).replace('.',''))
这就是vscode中的终端所说的:
Traceback (most recent call last):
File "c:/Users/User/Desktop/resistor2color_converter/resistor2colorcodes.py", line 60, in <module>
if value == 6 and key in x:
TypeError: argument of type 'float' is not iterable