How to remove ' ' from my list python 3.2

131 Views Asked by At
newlist=['21', '6', '13', '6', '11', '5', '6', '10', '11', '11', '21', '17', '23', '10', '36', '4', '4', '7', '23', '6', '12', '2', '7', '5', '14', '3', '10', '5', '9', '43', '38']

Now what I want to do with this list is take out the ' ' surrounding each integer, the problem is that the split() function or the strip() function wont work. So I don't know how to remove it. Help.

AttributeError: 'list' object has no attribute 'split' is given when I run.

Also After that I want to find the sum of each 7 integers in the list, and that I also don't know where to start. Any help would be appreciated.

4

There are 4 best solutions below

0
Zara On BEST ANSWER

What you have is a list of strings (hence the ''s), and you want to convert them to integers. The boring solution to the problem is a simple for loop:

for i in range(len(newlist)):
    newlist[i] = int(newlist[i]

The more compact method is a list comprehension, which you can read about here: List Comprehensions:

newlist = [int(num) for num in newlist]

The two functions you mentioned operate only on single strings.

>>> "Hi my name is Bob".split(" ")
["Hi", "my", "name", "is", "Bob"]
>>> "GARBAGE This string is surrounded by GARBAGE".strip("GARBAGE")
" This string is surrounded by "

As @Tomoko Sakurayama mentioned, you can sum simply enough with another loop. If you're feeling fancy, though, you can use another list comprehension (or even stack it on the old one, though that's not very Pythonic :).

[sum(newlist[i:i+7]) for i in range(0, len(newlist) - 6, 7)] + [sum(newlist[-(len(newlist) % 7):])]
0
Amin Guermazi On

You are probably looking for python's map function:

oldlist = ['21', '6', '13', '6', '11', '5', '6', '10', '11', '11', '21', '17', '23', '10', '36', '4', '4', '7', '23', '6', '12', '2', '7', '5', '14', '3', '10', '5', '9', '43', '38']
newlist = list(map(int, oldlist))

print(type(newlist[0]))
print(newlist) 

And output:

<class 'int'>

[21, 6, 13, 6, 11, 5, 6, 10, 11, 11, 21, 17, 23, 10, 36, 4, 4, 7, 23, 6, 12, 2, 7, 5, 14, 3, 10, 5, 9, 43, 38]
0
Yagiz Degirmenci On

You can use map for this case;

new_list = list(map(int, newlist))

print(new_list) == [21, 6, 13, 6, 11, 5, 6, 10, 11, 11, 21, 17, 23, 10, 36, 4, 4, 7, 23, 6, 12, 2, 7, 5, 14, 3, 10, 5, 9, 43, 38]
12
Tomoko Sakurayama On

That doesn't work because it is a list of strings rather than integers.

 x = [int(x) for x in newlist]

This will cast every value in the list to be an int.

Also After that I want to find the sum of each 7 integers in the list

^ Can you clarify what this means? Is this the sum of every seven consecutive numbers until the end of the list? If so,

sums = []
index = 0
for i in range(0, len(newlist), 7):
    sums[index] = sum(newlist[i : i + 7)])
    index += 1

EDIT: Full code:

x = [int(x) for x in newlist]
sums = []
for i in range(0, len(x), 7):
    sums.append(sum(x[i : i + 7]))