[英]How to divide one element to another element in a list in python
There is a couple of lists and I want to write a code thats input as DIVIDE,(fruit name) and the output is that fruits datas(5th lement/3rd element) from its list.For example one of the list is ['apple', 'a', 147, 457, 66, 119, 21, 6, 8] and the output is 0.26!有几个列表,我想编写一个输入为 DIVIDE(水果名称)的代码,output 是其列表中的水果数据(第 5 个元素/第 3 个元素)。例如,其中一个列表是 ['apple ', 'a', 147, 457, 66, 119, 21, 6, 8] 和 output 是 0.26!
fruits = [['apple', 'a', 147, 457, 66, 119, 21, 6, 8], ['banana', 'b', 131, 454, 53, 108, 19, 0, 20], ['orange', 'o', 124, 454, 54, 110, 20, 2, 29], 21]
command, name = input().split()
def count_machine(command, name):
if command == "DIVIDE" :
for fru in fruits:
if name == fru[0]:
result = [fru[5] / fru[3]]
return result
result = count_machine(command, name)
if type(result) == float:
print("%.2f" % result)
Where am i doing wrong,isn't it possible to divide [fru[5] / fru[3]] two elements like this?我在哪里做错了,难道不能像这样划分 [fru[5] / fru[3]] 两个元素吗?
Remove [] from result从结果中删除 []
if name == fru[0]:
result = [fru[5] / fru[3]]
Should be应该
if name == fru[0]:
result = fru[5] / fru[3]
As your code make result a list not a float由于您的代码使结果成为列表而不是浮点数
The result
returned is a list.返回的
result
是一个列表。 So, instead of checking for float type, do this to capture the float value-因此,不要检查浮点类型,而是执行此操作来捕获浮点值 -
if type(result) == list:
print("%.2f" % result[0])
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.