我正在编写一个代码,尝试从命令行获取 argv(i、w 或 f)。然后使用输入,我想要获取整数、 float 或单词的列表并执行一些操作。
- 用户将在命令行上输入“f”,然后输入浮点列表,其中的值将附加到空列表中。然后程序会对float列表进行排序并打印输出结果。
我想对单词和整数进行类似的处理。
如果输入是单词列表,输出将按字母顺序打印单词。如果输入是整数列表,则输出将是相反顺序的列表。
这是我到目前为止的代码,但截至目前,一些输入值只是将值附加到空列表中。我错过了什么导致代码无法正常执行?
例如,程序将通过添加程序名称和单词“w”来启动:
$ test.py w
>>> abc ABC def DEF
[ABC, DEF,abc,def] # list by length, alphabetizing words
代码
import sys, re
script, options = sys.argv[0], sys.argv[1:]
a = []
for line in options:
if re.search('f',line): # 'f' in the command line
a.append(input())
a.join(sorted(a)) # sort floating point ascending
print (a)
elif re.search('w', line):
a.append.sort(key=len, reverse=True) # print list in alphabetize order
print(a)
else: re.search('i', line)
a.append(input())
''.join(a)[::-1] # print list in reverse order
print (a)
最佳答案
试试这个:
import sys
option, values = sys.argv[1], sys.argv[2:]
tmp = {
'i': lambda v: map(int, v),
'w': lambda v: map(str, v),
'f': lambda v: map(float, v)
}
print(sorted(tmp[option](values)))
输出:
shell$ python my.py f 1.0 2.0 -1.0
[-1.0, 1.0, 2.0]
shell$
shell$ python my.py w aa bb cc
['aa', 'bb', 'cc']
shell$
shell$ python my.py i 10 20 30
[10, 20, 30]
shell$
您必须添加必要的错误处理。例如,
>>> float('aa')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: could not convert string to float: aa
>>>
关于Python - 列表的追加和排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36707886/