This question already has answers here:
Sum a list of lists to get a sum list Python
(2 answers)
Closed 5 years ago.
First off, I am really new to python, and programming in general, and I'm struggling to grasp the concept of nested for loops and nested lists.
In my code below I am trying to take each list inside the list list1 and sum them using a for loop. I am aware that the range function would help somehow.
Code:
def sum_list(list1):
list_of_sums = []
total = 0
for l in list1:
for value in l:
total = total + value
list_of_sums.append(total)
return list_of_sums
Input test:
list1 = [[4, 7, 9], [4, 5, 2], [4, 5, 6]]
print(sum_list(list1))
Output:
[4, 11, 20]
Desired output:
[20, 11, 15]
You have some logical issues in your code. Think carefully when you should reset total and when to append result to the list_of_sums.
def sum_list(list):
list_of_sums = []
for sublist in list:
total = 0
for value in sublist:
total += value
list_of_sums.append(total)
return list_of_sums
you can achieve this by using list comprehension, it's one of the best thing provided by python. it really shirnks you code and yet easy to understand.
following post my help. You can google more on list comprehension, if you like
http://treyhunner.com/2015/12/python-list-comprehensions-now-in-color/
def sum_list(list1):
return [sum(inner_list) for inner_list in list1]
print sum_list([[4, 7, 9], [4, 5, 2], [4, 5, 6]])
Related
This question already has answers here:
Python: Finding differences between elements of a list
(12 answers)
Closed 3 months ago.
list = [4, 7, 11, 15]
I'm trying to create a function to loop through list items, and find the difference between list[1] and list[0], and then list[2] and list[1], and then list[3] and list[2]... and so on for the entirety of the list. I am thinking of using a for loop but there might be a better way. Thanks.
output would be:
list_diff = [3, 4, 4]
def difference(list):
for items in list():
or
def difference(list):
list_diff.append(list[1] - list[0])
list_diff.append(list[2] - list[1])
etc.
...
If you are in Python 3.10+ you could try pairwise:
And you should try NOT to use the built-in list as the variable name.
It's quite easy and straightforward to make this one-line into a function.
from itertools import pairwise
>>>[b-a for a, b in pairwise(lst)] # List Comprehension
[3, 4, 4]
# Or just zip()
diffs = [b-a for a, b in zip(lst, lst[1:]) ] # no import
You can simply loop for each item starting from element 1:
def diff(source):
return [source[i] - source[i - 1] for i in range(1, len(source))]
print(diff([4, 7, 11, 15])) # [3, 4, 4]
num_list = [4, 7, 11, 15]
def difference(numbers):
diff_list = []
for i in range(1, len(numbers)):
diff_list.append(numbers[i] - numbers[i - 1])
return diff_list
print(difference(num_list)) # [3, 4, 4]
This question already has answers here:
How do I make a flat list out of a list of lists?
(34 answers)
Closed 4 years ago.
The given code flattens the vector but I'd like to understand the execution order of the two for loops. I've checked the Python Docs too but the execution pattern is not given.
>>> # flatten a list using a list comprehension with two 'for'
>>> vec = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
>>> [num for elem in vec for num in elem]
[1,2,3,4,5,6,7,8,9]
As I understand, execution order is like abstraction (left to right)? Is there any other opinion about it.
This link is flatten using lambda expression, and my question is regarding validation of two for loop execution in List Comp: How to make a flat list out of list of lists?
It works left to right and is the short form of:
vec = [[1,2,3], [4,5,6], [7,8,9]]
flatten = []
for elem in vec:
for num in elem:
flatten.append(num)
This will give you the same output as [num for elem in vec for num in elem].
[1, 2, 3, 4, 5, 6, 7, 8, 9]
You are right about it being left to right. It's true when you look at the equivalent too (because of indentation):
vec = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
output = []
for elem in vec: # first layer
for num in elem: # second layer
output.append(num)
I have a nested list (4 levels) and want to give out each list item (first level) as a new list. I know how to print this:
mynestedlist = [[([6, "x1a", "y1a"], [8, "x1b", "y1b"]), ([9, "x2a", "y2b"], [4, "x2b", "y2b"])],
[([6, "x1a", "y1a"], [9, "x2a", "y2b"]), ([8, "x1b", "y1b"], [4, "x2b", "y2b"])],
[([6, "x1a", "y1a"], [4, "x2b", "y2b"]), ([9, "x2a", "y2b"], [8, "x1b", "y1b"])]]
for i in range(0,len(mynestedlist)):
print(i)
print(mynestedlist[i])
But I want to give each item out as a new list. I can't do this because I do not know how to automatically change the name of the list so I don't overwrite my list in each loop.
I tried something like:
for i in range(0,len(mynestedlist)):
"list"+str(i) = [mynestedlist[i]]
but this doesn't work (obviously, I guess). Probably an easy question but I can't solve it, please help?
You can use Dictionary here , dictionary with "list + str(i)" key and value is desired list :
myDic = {}
for key,value in enumerate(mynestedlist,1):
myDic["list"+str(key)] = value
Result:
{'list3': [([6, 'x1a', 'y1a'], [4, 'x2b', 'y2b']), ([9, 'x2a', 'y2b'], [8, 'x1b', 'y1b'])], 'list1': [([6, 'x1a', 'y1a'], [8, 'x1b', 'y1b']), ([9, 'x2a', 'y2b'], [4, 'x2b', 'y2b'])], 'list2': [([6, 'x1a', 'y1a'], [9, 'x2a', 'y2b']), ([8, 'x1b', 'y1b'], [4, 'x2b', 'y2b'])]
For more information about dictionary visit here:
Python Dictionary
if I understand the question correctly, you would like to identify the last nest and its index in your nested list. the solution that I can think of is not straight forward though worth learning about:
def lastnest(nest, level=0, c=0):
level += 2
counter = 0
for j in nest:
if any([type(x) == list or type(x) == tuple for x in j]):
for i in j:
c += 1
if type(i) is list or type(i) is tuple:
lastnest(i, level=level, c=c)
else:
counter += 1
print level, (c-1)%len(j), counter, j
lastnest(mynestedlist)
this should print out the level, nest id and nest item index as well as the list itself, but it does assume that all the last nests will be of the same len()
This question already has answers here:
How do I split a list into equally-sized chunks?
(66 answers)
Closed 9 years ago.
Hi I am a beginner to python and I have an exam tomorrow. I do not know how to do this question. I know that I have to use a nested for loop but, I cannot make it work syntactically. Here is the question, I apologize for any formatting errors.
(list of int, int) -> list of (list of int)
Return a list of lists of elements from 1st,
where each sublist is the next num elements from 1st.
If the length of 1st is not a multiple of num, the final sublist will have fewer than num elements.
ยป> make_rows([2. 4, 6, 8, 10, 12],3) #Function call
[[2, 4, 6], [8, 10, 12]] # expected output
do something like this:
def separate(lst, index):
new_list = [lst[i:i+index] for i in range(0, len(lst), index)]
return new_list
it will return like so:
>>> print separate([1,2,3,4,5,6],3)
[[1, 2, 3], [4, 5, 6]]
Here is an extremely verbose solution that's not very Pythonic, but shows in detail the steps one would take without List comprehensions or functional style.
The original poster mentioned for-loops, so I thought he may want an iterative approach.
def make_rows(list_of_int, num_per_row):
new_list = []
count = 0
new_inner_list = []
for n in list_of_int:
count += 1
new_inner_list.append(n)
if (count == num_per_row):
new_list.append(new_inner_list)
new_inner_list = []
count = 0
return new_list
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Flatten (an irregular) list of lists in Python
for instance, from:
[[1,2,3],'a',[[4],[5,6],7]]
we want to flatten/penetrate the structure and get all the elements at bottom listed in a line:
[1,2,3,'a',4,5,6,7]
# a recursive function to flatten arbitrary nested lists into one simple 1D list
def flatten(inlist,outlist):
for e in inlist:
if isinstance(e,list) :
flatten(e,outlist)
else:
outlist.append(e)
it's a practice of recursive function, :). the "outlist" here serves as a reference for return-list.
there must be better structures...
;)
for example:
For your benefit, here is an implementation that modifies the list in-place:
def flatten_in_place(seq):
if isinstance(seq, list):
for index, item in reversed(list(enumerate(seq))):
if isinstance(item, list):
seq[index: index + 1] = fil(item)
return seq
else:
return [seq]
Usage:
>>> l = [[1, 2], [3, 4], 5, 6, [7, [8, 9]]]
>>> flatten_in_place(l)
>>> l
[1, 2, 3, 4, 5, 6, 7, 8, 9]
Interestingly enough, the timeit results (t = 1,000,000) show this to be slightly faster than your implementation:
flatten_in_place time: 4.88
flatten time: 5.16
I'm not sure why that is exactly. Any ideas?