【问题标题】:python dictionaries. Two strings as key蟒蛇词典。两个字符串作为键
【发布时间】:2022-01-13 20:35:49
【问题描述】:

我是 python 新手,想弄清楚如何将 3 个用空格分隔的字符串作为输入,然后前两个将是所需字典的键,第三个字符串将是键:

示例:

 John Smith 1234
 Mike Tyson 5678

字典应该是这样的:

{'John Smith': '1234', 'Mike Tyson': '5678'}

如果它只是两个非常简单的字符串并且我得到正确答案:

   count=int(input())
   d=dict(input().split() for x in range(count))
   print(d)

【问题讨论】:

    标签: python python-3.x dictionary


    【解决方案1】:

    您可以将rsplitmaxsplit=1 一起使用;这样,你只从右边分裂一次:

    lst = ['John Smith 1234', 'Mike Tyson 5678']
    d = {}
    for string in lst:
        s = string.rsplit(maxsplit=1)
        d[s[0]] = s[1]
    

    输出:

    {'John Smith': '1234', 'Mike Tyson': '5678'}
    

    【讨论】:

    • 这里您已经将字符串放入列表中,但在实际场景中,您需要将它们作为用户输入,然后转换为列表?
    • 没有;每个都在不同的行:第一行:John Smith 1234 第二行 Mike Tyson 5678
    • 不完全...代码经过一个循环,并根据范围,它将在每一行中从用户那里获取一个新输入。所以如果 n 为 = 2,则首先输入:John Smith 1234 hit输入和下一行第二个输入:Mike Tyson 5678
    • @moin1010 你怎么存储用户输入的?大概在一个列表中,对吧?
    • @moin1010 然后代码将按照编写的方式运行
    【解决方案2】:
    # generator to yield input until an empty string is entered
    def get_input():
        s = input()
        while s:
            yield s
            s = input()
    
    # get input from the generator, split at the last " " and make a dict from it
    d = dict(line.rsplit(maxsplit=1) for line in get_input())
    

    开始时选择循环次数的函数:

    def get_input():
        count = int(input("how many entries: "))
        for _ in range(count):
            yield input()
    

    【讨论】:

    • 非常接近我正在寻找的内容,但它应该基于一个整数作为用户的第一个输入循环而不是空字符串:前输入:2 john smith 123 mike tyson 456 输出:{'约翰史密斯':'1234','迈克泰森':'5678'}
    【解决方案3】:

    假设字符串输入固定为 = 3,并且您要将字符串接收到列表中:

    from functools import reduce
    
    S = ["John Smith 1234", "Mike Tyson 5678"]
    
    reduce(lambda x,y: dict(x, **y), [dict([[" ".join(s.split()[:2]),s.split()[-1]]]) for s in S])
    
    >> {'John Smith': '1234', 'Mike Tyson': '5678'}
    

    【讨论】:

      【解决方案4】:

      你可以使用 rsplit last item。

      
      count = int(input("How many times data you want to enter: "))
      data_list = [input("Please enter the {} data: ".format(x + 1)) for x in range(count)]
      
      output_dict = dict(item.rsplit(' ', 1) for item in data_list)
      print("Output:\n", output_dict)
      >>
      

      输出:

      How many times data you want to enter: 2
      Please enter the 1 data: John Smith 1234
      Please enter the 2 data: Mike Tyson 5678
      Output:
       {'John Smith': '1234', 'Mike Tyson': '5678'}
      

      【讨论】:

        【解决方案5】:

        可以使用str.rpartition()。这将返回前两个字符串、空格和最终字符串的元组。 (Python 3.10)

        s = input()
        key, space, final = s.rpartition(' ')
        d = {key:final}
        

        【讨论】:

          猜你喜欢
          • 2022-11-16
          • 2020-03-17
          • 1970-01-01
          • 2020-08-08
          • 2011-06-30
          • 2018-05-13
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多