0

What would be the most efficient way of inverting (i.e. multiplying with -1) the integers in the strings in a list using python?

Example input:

['-1 -2 -3 -4 -5 -6 -7 -8 9 -10 11',' -17 18 19 20 -21 22 -23 ',' -36 -37 -38 39 40 41 42 -43 44 ']

Desired output:

['1 2 3 4 5 6 7 8 -9 10 -11', '17 -18 -19 -20 21 -22 23', '36 37 38 -39 -40 -41 -42 43 -44']
4
  • 4
    What do you mean "invert"? What is the output you expect here? Commented Dec 22, 2015 at 21:13
  • 1
    Need more precise info about what you want the output to look like. Also need to know what approach you've tried and why it doesn't work. Commented Dec 22, 2015 at 21:13
  • Do you really have a list of strings with numbers written in the string? or do you have a list of lists? Commented Dec 22, 2015 at 21:14
  • Yes, I have list of strings with numbers written in the string.I am reading these numbers from separate files. Commented Dec 22, 2015 at 21:19

3 Answers 3

4

Using simple list comprehensions

>>> lst = ['-1 -2 -3 -4 -5 -6 -7 -8 9 -10 11',' -17 18 19 20 -21 22 -23 ',' -36 -37 -38 39 40 41 42 -43 44 ']
>>> [' '.join(map(lambda x: str(-int(x)), s.split())) for s in lst]
['1 2 3 4 5 6 7 8 -9 10 -11', '17 -18 -19 -20 21 -22 23', '36 37 38 -39 -40 -41 -42 43 -44']
Sign up to request clarification or add additional context in comments.

Comments

2

This does what you want. Hopefully the variable and function names make it relatively clear what's going on.

list_of_strings = ['-1 -2 -3 -4 -5 -6 -7 -8 9 -10 11',' -17 18 19 20 -21 22 -23 ',' -36 -37 -38 39 40 41 42 -43 44 ']

def process(string_of_ints):
    return ' '.join( str(-int(each_word)) for each_word in string_of_ints.split() )

result = [ process(each_string) for each_string in list_of_strings ]
print(result)

It can be collapsed into one line at the cost of some clarity:

result = [ ' '.join( str(-int(each_word)) for each_word in each_string.split() ) for each_string in list_of_strings ]

(NB: "invert" is really a potentially misleading word - in mathematics, when used unqualified, the most common interpretation means do 1/x, not -x; in computing it might mean any one of a number of different things, including reversing the order of a sequence).

1 Comment

Sorry about the misunderstanding, will be more precise the next time
1

A slightly different approach then what has been posted so far

l=['-1 -2 -3 -4 -5 -6 -7 -8 9 -10 11',' -17 18 19 20 -21 22 -23 ',' -36 -37 -38 39 40 41 42 -43 44 ']

for i in xrange(len(l)):
    tmp=[]
    for s in l[i].split():
        tmp.append(str(-int(s)))
    l[i]=' '.join(tmp)
print l

['1 2 3 4 5 6 7 8 -9 10 -11', '17 -18 -19 -20 21 -22 23', '36 37 38 -39 -40 -41 -42 43 -44']

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.