【问题标题】:How do I create an array of strings through user inputs and print them lexicographically in Python?如何通过用户输入创建字符串数组并在 Python 中按字典顺序打印它们?
【发布时间】:2019-02-08 00:10:50
【问题描述】:

我正在尝试创建一个小程序,提示用户输入 3 个单词,然后将字符串输入放入一个数组中,然后按字典顺序对数组进行排序并将数组打印为字符串列表。

我尝试了 .sort 函数,但它不起作用。我正在进行的项目不需要循环知识(我还没有很多经验)。

    a = []
    first = input("Type a word: ")
    second = input("Type another word: ")
    third = input("Type the last word: ")
    a += first
    a += second
    a += third

    a = sorted(a)

    print(a)

我希望打印的结果是用逗号分隔的三个单词

 Apple, Banana, Egg

相反,我的代码打印

 ['A', 'B', 'E', 'a', 'a', 'a', 'e', 'g', 'g', 'l', 'n', 'n', 'p', 'p']

【问题讨论】:

    标签: python arrays string list sorting


    【解决方案1】:

    问题是列表上的+= 是两个列表的串联......因此python 将您的字符串“Apple”解释为(未打包的)列表['A', 'p', 'p', 'l', 'e']

    两种不同的解决方案:

    1) 将输入设为包含单词的单个列表:

    a = []
    first = input("Type a word: ")
    second = input("Type another word: ")
    third = input("Type the last word: ")
    a += [first]
    a += [second]
    a += [third]
    
    a = sorted(a)
    
    print(a)
    

    2) 只需使用 append 方法,它需要一个元素。

    a = []
    first = input("Type a word: ")
    second = input("Type another word: ")
    third = input("Type the last word: ")
    a.append(first)
    a.append(second)
    a.append(third)
    
    a = sorted(a)
    
    print(a)
    

    【讨论】:

      【解决方案2】:

      添加到列表的最佳方法是使用.append

      在你的情况下,我会这样做:

      a = []
      
      first = input("Type a word: ")
      second = input("Type another word: ")
      third = input("Type the last word: ")
      
      a.append(first)
      a.append(second)
      a.append(third)
      
      print(sorted(a))
      

      将数字添加到数组(在 Python 中称为列表)后,只需使用 sorted() 方法按字典顺序对单词进行排序!

      【讨论】:

        【解决方案3】:

        您不应将输入单词添加到列表中,而应附加它。当您将字符串添加到列表中时,它会将字符串分解为每个字符,然后将其添加。因为您不能将一种类型的数据添加到另一种类型的数据(就像您不能添加“1”+3,除非它是 JS 但它完全不同)。

        因此,您应该附加单词,然后使用 {}.sort() 方法对列表进行排序并将其连接成一个字符串。

        a = []
        
        first = input("Type a word: ")
        second = input("Type another word: ")
        third = input("Type the last word: ")
        
        a.append(first)
        a.append(second)
        a.append(third)
        
        a.sort()
        finalString = ','.join(a)
        
        print(finalString)
        

        【讨论】:

          猜你喜欢
          • 2019-06-27
          • 1970-01-01
          • 2018-05-16
          • 2020-04-11
          • 2021-06-29
          • 2017-07-12
          • 2017-04-02
          • 2013-12-05
          • 1970-01-01
          相关资源
          最近更新 更多