繁体   English   中英

打印正在以相反的字母顺序打印所有字母而不是单词

[英]Print is printing all the letters instead of words in reverse alphabetical order

我需要打印用户从命令行输入的单词列表。 现在,字母顺序可以正常工作,但是当我反向打印时,它不会正确显示。 我尝试了很多东西,但我现在没有想法。 任何人? 这是代码:

import argparse

argparser = argparse.ArgumentParser()
argparser.add_argument("user_string", help = 'User string')
argparser.add_argument("--reverse", "-r", action="store_true", dest="reverseflag")
args = argparser.parse_args()
user_string = args.user_string
words_to_sort = user_string.split()
if len(words_to_sort) < 2:
        args.user_string
        # alerts user to input more than 1 word
        print("Invalid command line arguments to program. Please, supply two or more strings to sort.")

if len(words_to_sort) > 1 and (args.reverseflag == True):
        words_to_sort = sorted(args.user_string, reverse=True)
        print(*words_to_sort)
else:
        words_to_sort.sort()
        for word in words_to_sort:
            print(word)

这是我从命令行得到的:

PS C:\Users\desktop\folder> python mysort.py --reverse "all mall ball"
m l l l l l l b a a a
PS C:\Users\desktop\folder> python mysort.py "all mall ball"
all
ball
mall

反向应该只是将数组从 z 反转为 a 但遗憾的是事实并非如此。

如果 reverse 为 True,则您的代码将用户输入视为一个巨大的字符串:

words_to_sort = sorted(args.user_string, reverse=True)

相反,您需要传入字符串列表,即words_to_sort

words_to_sort = sorted(words_to_sort, reverse=True)

排序需要一个可迭代的。 在您的情况下,它将字符串拆分为其字符。 也许,您应该考虑一下: sorted(text.split(), reverse=True)

您出于某种原因对args.user_string进行排序。 您应该只对words_to_sort进行排序。 因为args.reverseflag已经是 Boolean,所以您可以简单地将它传递给.sort 摆脱你的整个if - else块并将其替换为

words_to_sort.sort(reverse=args.reverseflag)
for word in words_to_sort:
    print(word)

您正在对输入字符串而不是单词列表进行排序

if len(words_to_sort) > 1 and (args.reverseflag == True):
    words_to_sort = sorted(args.user_string, reverse=True)
    print(*words_to_sort)

改为排序 words_to_sort

if len(words_to_sort) > 1 and (args.reverseflag == True):
    words_to_sort = sorted(words_to_sort, reverse=True)
    print(*words_to_sort)

您实际上可以在 if/else 之前对其进行排序,然后将列表反转

args = argparser.parse_args()
user_string = args.user_string
words = sorted(user_string.split())
if len(words) < 2:
    args.user_string
    # alerts user to input more than 1 word
    print("Invalid command line arguments to program. Please, supply two or more strings to sort.")

if args.reverseflag:
    print(*words[::-1])
else:
    print(*words)

暂无
暂无

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

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