Python-追加和排序列表 [英] Python - Appending and Sorting a List
问题描述
我正在尝试从命令行获取argv(i,w或f)的代码.然后使用输入,我要获取一个整数列表,浮点数或单词并执行一些操作.
I'm working on a code where I'm trying to take a argv (i, w or f) from the command line. Then using input, I want to take a list of integers, float or words and execute a few things.
- 用户将在命令行上输入'f',然后输入浮点列表,这些浮点值将附加到一个空列表中.然后程序将对float列表进行排序并打印输出结果.
我想要类似的单词和整数.
I want to similar for words and integers.
如果输入是单词列表,则输出将按字母顺序打印单词.如果输入是整数列表,则输出将是相反顺序的列表.
If the input is a list of words, the output will print words in alphabetize order. If the input is a list of integers, the output will be the list in the reverse order.
这是我到目前为止的代码,但是到目前为止,一些输入值只是将这些值附加到空列表中.我缺少什么阻止了代码正常执行?
This is the code that I have so far, but as of right now some of the input values are just appending the values to the empty list. What am I missing that is preventing the code to execute properly?
例如,程序将以添加程序名称和单词"w"开头:
for example, program will start by adding program name and 'w' for word:
$ 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$
您将必须添加必要的错误处理.例如,
You'll have to add necessary error handling. For e.g,
>>> float('aa')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: could not convert string to float: aa
>>>
这篇关于Python-追加和排序列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!