brazjul
brazjul

Reputation: 339

Python - Appending and Sorting a List

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.

  1. User will enter 'f' on the command line and then input a list of floating points where the values will append to an empty list. Then the program will sort the list of float and print the output results.

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?

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 

code

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)  

Upvotes: 1

Views: 1351

Answers (1)

Sharad
Sharad

Reputation: 10622

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 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
 >>> 

Upvotes: 1

Related Questions