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.
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]))
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):])]
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]
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]
Related
I want my code to cycle through each item of the list and convert it from str to int but it only converts half of the list and in an irregular order.
My code:
for item in list:
list.append(int(item))
list.remove(item)
print (list)
For example if list is ['5', '6', '3', '5', '6', '2', '6', '8', '5', '4', '2', '8']
The final would be ['6', '8', '5', '4', '2', '8', 3, 6, 2, 6, 5, 5]
Which is only half converted and not in order.
I could do it another way but that is a lot longer so would like to fix this and add to my knowledge about for loops.
My knowledge and experience with Python is tiny, so I most probably won't understand unless it's really basic and jargon is explained.
Using list comprehension:
l = ['5', '6', '3', '5', '6', '2', '6', '8', '5', '4', '2', '8']
output = [int(i) for i in l]
print(output)
[5, 6, 3, 5, 6, 2, 6, 8, 5, 4, 2, 8]
If you don't understand list comprehension you could use simple for loop:
l1 = []
for i in l:
l1.append(int(i))
print(l1)
[5, 6, 3, 5, 6, 2, 6, 8, 5, 4, 2, 8]
Both answers above are good but why your code didn't work also should be adressed.
First , you are changing the list while you are iterating on it. This is something you should not do. It will probably cause problems, like in your question.
Second, remove method removes the first element in the list that it encounters which fits the given argument, it also should be used with care.
Third, you should not use list as an variable name. As it is a built-in class.
for item in list:
print (list)
list.append(int(item))
list.remove(item)
# Prints
['5', '6', '3', '5', '6', '2', '6', '8', '5', '4', '2', '8']
['6', '3', '5', '6', '2', '6', '8', '5', '4', '2', '8', 5]
['6', '5', '6', '2', '6', '8', '5', '4', '2', '8', 5, 3]
['5', '6', '2', '6', '8', '5', '4', '2', '8', 5, 3, 6]
['5', '2', '6', '8', '5', '4', '2', '8', 5, 3, 6, 6]
['2', '6', '8', '5', '4', '2', '8', 5, 3, 6, 6, 5]
['6', '8', '5', '4', '2', '8', 5, 3, 6, 6, 5, 2]
['6', '8', '5', '4', '2', '8', 3, 6, 6, 5, 2, 5]
['6', '8', '5', '4', '2', '8', 3, 6, 5, 2, 5, 6]
['6', '8', '5', '4', '2', '8', 3, 6, 2, 5, 6, 5]
['6', '8', '5', '4', '2', '8', 3, 6, 2, 6, 5, 5]
['6', '8', '5', '4', '2', '8', 3, 6, 2, 6, 5, 5]
['6', '8', '5', '4', '2', '8', 3, 6, 2, 6, 5, 5]
As you see, not working as expected
Why don't you use something like this:
l = list(map(int, l))
It simply calls function int on each item from l.
Here's doc.
While the other two answers give you better ways of converting your list of strings to integers, they really don't answer your question. Your main problem is that you are mutating (altering) the list structure while your for loop operates on it. You should not mutate the list structure (remove elements or append) because the loop iteration variable item gets out of sync. There's no way to re-sync item to the new list structure.
BTW: It's not a random order. It's every other item.
You could write your conversion loop like so, because you're not mutating the structure of the list, only the individual elements:
for i in xrange(len(l)):
l[i] = int(l[i])
Don't write it like this:
for item in l:
item = int(item)
It doesn't mutate the individual list elements, even though you would think that it does. It has to do with how Python iterators work.
Try this:
>>> list = ['5', '6', '3', '5', '6', '2', '6', '8', '5', '4', '2', '8']
>>> for item in list[:]:
... list.append(int(item))
... list.remove(item)
...
>>> print(list)
[5, 6, 3, 5, 6, 2, 6, 8, 5, 4, 2, 8]
Explanation: Here we are iterating over a clone of the list but doing operations on the original list.
PS: list is a keyword in python. Its usage as a variable name should be avoided.
I have a list of strings that look like this, and I need to add the first, second, and third entry of each to a integer list a b and c accordingly
print cuts gives me
[['3', '5', '10'], ['2', '8', '15'], ['7', '9', '25'], ['4', '6', '20'], ['9', '12', '50'], ['5', '7', '22'], ['3', '8', '17'], ['6', '9', '24'], ['8', '11', '40'], ['7', '10', '30'], []]
such that
a = [3,2,7, ... , 7]
b = [5, 8, 9, ... , 10]
c = [10, 15, ... , 30]
(Also want these to be ints not strings)
I tried to delimit by
cuts[i] = cuts[i].strip(",")
thinking that it would give me [[3] [5] [10] ] which would let me add with a for loop but python told me lists don't have a strip attribute
Here are list comprehensions in basic form:
data = [['3', '5', '10'], ['2', '8', '15'], ['7', '9', '25'], ['4', '6', '20'],
['9', '12', '50'], ['5', '7', '22'], ['3', '8', '17'], ['6', '9', '24'],
['8', '11', '40'], ['7', '10', '30'], []]
a = [int(x[0]) for x in data if len(x) >= 1]
b = [int(x[1]) for x in data if len(x) >= 2]
c = [int(x[2]) for x in data if len(x) >= 3]
print a
print b
print c
Or, to keep them in a 2-dimensional list:
abc = [[int(x[i]) for x in data if len(x) >= i+1] for i in range(len(data[0]))]
print abc
Output:
[[3, 2, 7, 4, 9, 5, 3, 6, 8, 7],
[5, 8, 9, 6, 12, 7, 8, 9, 11, 10],
[10, 15, 25, 20, 50, 22, 17, 24, 40, 30]]
This can be done using the built in zip function.
a, b, c = zip(*cuts)
You can read about zip here. The gist is here -
this function returns a list of tuples, where the i-th tuple contains
the i-th element from each of the argument sequences or iterables
If you then want your lists to hold numbers instead of strings, you can map them over the int function.
a = map(int, a)
b = map(int, b)
c = map(int, c)
I'm assuming that the empty list at the end of cuts is a typo -- otherwise your requirements don't quite make sense since there isn't a first, second and third element of an empty list. You could always use
cuts = [cut for cut in cuts if len(cut) > 0]
if you want to cut cuts down to size.
In any event, once that empty list is removed, what you are asking for is a sort of zip and can be done like thus:
>>> cuts = [['3', '5', '10'], ['2', '8', '15'], ['7', '9', '25'], ['4', '6', '20'], ['9', '12', '50'], ['5', '7', '22'], ['3', '8', '17'], ['6', '9', '24'], ['8', '11', '40'], ['7', '10', '30']]
>>> a,b,c = ([int(s) for s in strings] for strings in zip(*cuts))
>>> a
[3, 2, 7, 4, 9, 5, 3, 6, 8, 7]
>>> b
[5, 8, 9, 6, 12, 7, 8, 9, 11, 10]
>>> c
[10, 15, 25, 20, 50, 22, 17, 24, 40, 30]
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 7 years ago.
Improve this question
I need some help extracting 6 numbers from a text file and then extracting the next 6 numbers but separating them in groups. In total, I should have 8 groups of 6 numbers.
def oly():
my_file=open("/Users/Mariano/Google Drive/Radio Show/Junior & Plundhy Show/shoedata.txt","r")
line=my_file.readline()
for line in range(0,0):
print (line,)
while line:
print (line,)
line=my_file.readline()
You can str.split on whitespace and then split into n size chunks:
with open("/Users/Mariano/Google Drive/Radio Show/Junior & Plundhy Show/shoedata.txt") as f: # with closes you files
nums = f.read().split() # split line into individual elements
# get 6 element slices from nums
for chk in (nums[i:i+6] for i in range(0, len(nums), 6)):
print(chk)
['6', '7', '3', '9', '6', '6']
['5', '5', '5', '5', '5', '5']
['2', '3', '4', '5', '6', '7']
['8', '4', '7', '8', '9', '10']
['2', '6', '10', '2', '4', '5']
['10', '8', '10', '8', '7', '6']
['5', '4', '3', '2', '7', '5']
['5', '4', '5', '4', '5', '4']
If you need actual ints then map each row to int:
for chk in (nums[i:i+6] for i in range(0, len(nums), 6)):
print(list(map(int, chk)))
[6, 7, 3, 9, 6, 6]
[5, 5, 5, 5, 5, 5]
[2, 3, 4, 5, 6, 7]
[8, 4, 7, 8, 9, 10]
[2, 6, 10, 2, 4, 5]
[10, 8, 10, 8, 7, 6]
[5, 4, 3, 2, 7, 5]
[5, 4, 5, 4, 5, 4]
If using python2 use xrange and you don't need to call list on map.
I have a list like this ['1000', '6', '1', '5', '14', '34', '43', '3', '18', '28', '16'] I want like this [1000, 6, 1, 5, 14, 34, 43, 3, 18, 28, 16] How to do this in python.
If I understand you right you have list of strings and want to get list of integers.
This can be easily done by:
lst = [int(item) for item in lst]
For example:
>>> lst = ['1000', '6', '1', '5', '14', '34', '43', '3', '18', '28', '16']
>>> lst
['1000', '6', '1', '5', '14', '34', '43', '3', '18', '28', '16']
>>> lst = [int(item) for item in lst]
>>> lst
[1000, 6, 1, 5, 14, 34, 43, 3, 18, 28, 16]
You can convert each element into an Integer.
>>> lst_string = ['1000', '6', '1', '5', '14', '34', '43', '3', '18', '28', '16']
>>> lst_int = [int(n) for n in lst_string]
>>> print lst_int
[1000, 6, 1, 5, 14, 34, 43, 3, 18, 28, 16]
Or you can use the map-function which performs a function on a sequence. In this case we perform the int-function to your list.
>>> map(int, lst_string)
[1000, 6, 1, 5, 14, 34, 43, 3, 18, 28, 16]
I have a list of integers in string representation, similar to the following:
L1 = ['11', '10', '13', '12',
'15', '14', '1', '3',
'2', '5', '4', '7',
'6', '9', '8']
I need to make it a list of integers like:
L2 = [11, 10, 13, 12, 15, 14, 1, 3, 2, 5, 4, 7, 6, 9, 8]
Finally I will sort it like below:
L3 = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15] # by L2.sort()
Please let me know what is the best way to get from L1 to L3?
You could do it in one step like this:
L3 = sorted(map(int, L1))
In more detail, here are the steps:
>>> L1 = ['11', '10', '13', '12', '15', '14', '1', '3', '2', '5', '4', '7', '6', '9', '8']
>>> L1
['11', '10', '13', '12', '15', '14', '1', '3', '2', '5', '4', '7', '6', '9', '8']
>>> map(int, L1)
[11, 10, 13, 12, 15, 14, 1, 3, 2, 5, 4, 7, 6, 9, 8]
>>> sorted(_)
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15]
>>>
>>> L1 = ['11', '10', '13', '12', '15', '14', '1', '3', '2', '5', '4', '7', '6', '9', '8']
>>> L1 = [int(x) for x in L1]
>>> L1
[11, 10, 13, 12, 15, 14, 1, 3, 2, 5, 4, 7, 6, 9, 8]
>>> L1.sort()
>>> L1
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15]
>>> L3 = L1
L3 = sorted(int(x) for x in L1)