Python - Appending and Sorting a List -
i'm working on code i'm trying take argv (i, w or f) command line. using input, want take list of integers, float or words , execute few things.
- user enter 'f' on command line , input list of floating points values append empty list. program sort list of float , print output results.
i want similar words , integers.
if input list of words, output print words in alphabetize order. if input list of integers, output list in reverse order.
this code have far, of right of input values appending values empty list. missing preventing code execute properly?
for example, program start adding program name , 'w' word:
$ test.py w >>> abc abc def def [abc, def,abc,def] # list length, alphabetizing words
code
import sys, re script, options = sys.argv[0], sys.argv[1:] = [] line in options: if re.search('f',line): # 'f' in 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)
try this:
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)))
output:
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 10 20 30 [10, 20, 30] shell$
you'll have add necessary error handling. e.g,
>>> float('aa') traceback (most recent call last): file "<stdin>", line 1, in <module> valueerror: not convert string float: aa >>>
Comments
Post a Comment