简体   繁体   English

如何拆分输入以创建字典?

[英]How to split input to create dictionary?

So I'm a complete noob (as in I'm taking my first class rn), and I can't figure out how to do this.所以我是一个完全的菜鸟(就像我正在服用我的第一个 class rn),我不知道该怎么做。 I receive an input for a future dictionary key and values corresponding to said key in one line from the user like so:我从用户那里收到一个未来字典键的输入和与所述键对应的值,如下所示:

fruitone = input("Please enter fruit name and values")

The input would be something like: apple 0.5 0.6 1.5.输入类似于:apple 0.5 0.6 1.5。 No commas or anything, just good ol' spaces.没有逗号或任何东西,只有很好的空格。 Eventually, this becomes:最终,这变成:

fruits = {'Apple': [0.5, 0.6, 1.5], 'Orange': [0.25, 0.4, 0.05]}

The issue I'm having is figuring out how to split this up so I can transform the input from one whole string into a string and multiple float objects that I can shove into a dictionary.我遇到的问题是弄清楚如何将其拆分,这样我就可以将输入从一个完整的字符串转换为一个字符串和多个可以塞入字典的浮点对象。 Please help?请帮忙?

dict_ ={}
strA = "apple 0.5 0.6 1.5"
strA = strA.split(' ')

dict_[strA[0]] = strA[1:]

O/p: {'apple': ['0.5', '0.6', '1.5']} O/p: {'apple': ['0.5', '0.6', '1.5']}

Use your input() as the string strA each time.每次使用您的 input() 作为字符串 strA 。

split is extremely powerful. split非常强大。 You should look up the Python documentation to understand more on how to exploit it.您应该查阅 Python 文档以了解更多关于如何利用它的信息。

You could build a dictionary like this你可以像这样建立一个字典

output = {}
latest_thing = "the current fruit"
for thing in fruitone.split(" "):
    if thing.replace('.','',1).isdigit():
        output[latest_thing].append(float(thing))
    else:
        output[thing] = []
        latest_thing = thing

assuming your input look like假设您的输入看起来像

apple 0.5 0.6 1.5 orange 0.25 0.4 0.05苹果 0.5 0.6 1.5 橙子 0.25 0.4 0.05

fruits = {}


def get_inp():
    inp = input("Please enter fruit name and values: ")
    inp_values = inp.split(" ")
    if len(inp_values) == 4:
        key = inp_values[0]
        try:
            value = list(map(float, inp_values[1:]))
        except ValueError:
            print("Invalid")
            return
        fruits[key] = value
    else:
        print("Invalid")
        return


get_inp()

I'm assuming that you want each fruit to be associated with exactly 3 floats.我假设您希望每个水果都与 3 个浮点数相关联。 Take input from the console and split it into a list of strings, dividing at every space.从控制台获取输入并将其拆分为字符串列表,并在每个空格处进行划分。 Exit if the resulting list is anything other than 4 elements long (for the fruit and 3 floats), then use map() to try to convert the number inputs to float values and then put them in a list, exiting if the conversion fails.如果结果列表的长度不是 4 个元素(对于水果和 3 个浮点数),则退出,然后使用map()尝试将数字输入转换为浮点值,然后将它们放入列表中,如果转换失败则退出。 Add the fruit string and resulting float list to the dictionary.将水果字符串和结果浮点列表添加到字典中。

Please check below code:请检查以下代码:

fruitone = input("Please enter fruit name and values")
fruits = {}
for element in fruitone.split():
    if element.isalpha():
        fruits[element]=[]
        temp = element
    else:
        fruits[temp].append(float(element))
print(fruits)

Input: apple 0.5 0.6 1.5 orange 0.25 0.4 0.05 Output by above code: {'apple': [0.5, 0.6, 1.5], 'orange': [0.25, 0.4, 0.05]}输入:apple 0.5 0.6 1.5 orange 0.25 0.4 0.05 Output 通过上述代码:{'apple': [0.5, 0.6, 1.5], 'orange': [0.25, 0.4, 0.05]}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM