简体   繁体   English

如何在 python 的列表中将一个元素划分为另一个元素

[英]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.

相关问题 根据另一个列表中的元素进行列表划分 - List divide based on element from another list 如果一个列表中的元素存在于 Python 中的另一个列表中,如何打印该元素? - How to print an element from one list if it exists in another list in Python? 如何在python中将一个元素从列表移动到另一个 - how to move one element from a list to another in python 在python中将元素从一个列表复制到另一个 - Copying element from one list to another in python 如何将一个元素与嵌套列表中的另一个元素进行比较? (在蟒蛇中) - How to compare an element to another element , that is inside a nested list? (in python) Python将更改的元素从一个列表返回到另一个列表的最快方法 - Python fastest way to return changed element from one list to another 如何根据另一个列表从python列表中获取元素 - How to get element from a python list based on another list 如何将一个列表中的元素指定为另一个列表中元素的值并打印结果? - How do I assign an element from one list as the value of an element from another list and print the result? 如何使用python比较列表中的元素并检查第一个列表元素是否包含在另一个列表的元素中 - How to compare elements in lists and check if first list element contains in another list's element using python 如何创建一个新列表,每个元素都是python中另一个列表的每个元素的正则表达式? - How can I create a new list with each element a regular expression of each element of another list in python?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM