appending list of numbers to new list python - python

This is kind of hard to describe so I'll show it mainly in code. I'm taking a List of a List of numbers and appending it to a masterList.
The first list in master list would be the first element of each list. I would insert 0 in it's appropriate index in the master list. Then I would move on to the next list. I would choose the first element of the 2nd list and append it to the second list in the master list, since it's index would be 1, I would insert 0 to the first index of that list. This is WAY confusing, please comment back if you have any questions about it. I'll answer back fast. This is really bugging me.
ex:
L = [[], [346], [113, 240], [2974, 1520, 684], [169, 1867, 41, 5795]]
What i want is this:
[[0,346,113,2974,169],[346,0,240,1520,1867],[113,240,0,684,41],[2974,1520,684,0,5795],[169,1867,41,5795,0]]

IIUC, you want something like
>>> L = [[], [346], [113, 240], [2974, 1520, 684], [169, 1867, 41, 5795]]
>>> [x+[0]+[L[j][i] for j in range(i+1, len(L))] for i, x in enumerate(L)]
[[0, 346, 113, 2974, 169], [346, 0, 240, 1520, 1867],
[113, 240, 0, 684, 41], [2974, 1520, 684, 0, 5795],
[169, 1867, 41, 5795, 0]]
which might be easier to read in expanded form:
combined = []
for i, x in enumerate(L):
newlist = x + [0]
for j in range(i+1, len(L)):
newlist.append(L[j][i])
combined.append(newlist)

Related

How to sum every element in a list with the previous one?

I would like to receive the following result,
Example:
list1 = [145, 100, 125, 134, 556]
with the output being a new list with the sum results like this:
list2 = [145, 245, 225, 259, 690]
You can also use the zip trick:
>>> list(map(sum, zip(list1, [0]+list1)))
[145, 245, 225, 259, 690]
If you don't mind getting a little bit esoteric, this can be done in a single comprehension without copying the original list:
In [14]: list_1 = [145, 100, 125, 134, 556]
...: b = 0
...: list_2 = [b + (b := a) for a in list_1]
...: list_2
Out[14]: [145, 245, 225, 259, 690]
This is similar to Selcuk's answer but may be a little simpler:
list2 = [a + b for a, b in zip(list1, [0]+list1)]
Or if you don't want to use zip;
list2 = [
list1[i] + (list1[i-1] if i > 0 else 0)
for i in range(len(list1))
]
I suggest using list comprehension for this.
list1 = [145,100,125,134,556]
newLst = [list1[0]]+[sum([list1[i],list1[i-1]]) for i in range(1,len(list1))]
output
[145, 245, 225, 259, 690]
My two cents
list1 = [145,100,125,134,556]
list2 = [val if not idx else val + list1[idx - 1] for idx, val in enumerate(list1)]
I didn't come up with a list comprehension idea.
But if you wanna brute force, it'll be:
list1 = [145, 100, 125, 134, 556]
list2 = [list1[0]]
for i in range(1, len(list1)):
list2.append(list1[i] + list1[i-1])
print(list2)
And you can get
[145, 245, 225, 259, 690]
Python to the old school style!. I have created this function that takes as parameter a list and return a new list with the previous element summed. I hope can help you
def sum_list(list_numbers):
index = 0
list2 = [list_numbers[index]]
while index < (len(list_numbers) - 1):
item = list_numbers[index] + list_numbers[index + 1]
list2.append(item)
index += 1
return list2
print(sum_list(list1))
Output:
[145, 245, 225, 259, 690]
Edit: I wanted to challenge myself using a recursion approach. Maybe it's not the best approach but is here:
list2 = []
def sum_list_recursion(first_element, list_numbers, max_length):
if len(list_numbers) == 0:
return list2
elif len(list_numbers) == max_length:
list2.append(first_element)
next_element = list_numbers[0]
list_numbers = list_numbers[1:]
else:
next_element = list_numbers[0]
list_numbers = list_numbers[1:]
list2.append((first_element + next_element))
sum_list_recursion(next_element, list_numbers, max_length)
sum_list_recursion(list1[0], list1, len(list1))
print(list2)
Output:
[145, 245, 225, 259, 690]

How to compare elements in list-of-lists?

I have a list which contains list of elements(the number of elements in each inner list are not same) and I want to group all the elements in same index into separate groups and return maximum values in each group:
for example,
elements = [[89, 213, 317], [106, 191, 314], [87]]
I want to group these elements like this,
groups = [[89,106,87],[213,191],[317,314]]
the expected result is the maximum values of each list in groups : 106 ,213 and 317
I tried to group elements using following code:
w = zip(*elements)
result_list = list(w)
print(result_list)
output I got is
[(89, 106, 87)]
You can use itertools.zip_longest with fillvalue=float("-inf"):
from itertools import zip_longest
elements = [[89, 213, 317], [106, 191, 314], [87]]
out = [max(t) for t in zip_longest(*elements, fillvalue=float("-inf"))]
print(out)
Prints:
[106, 213, 317]
NOTE: zip() won't work here, because (as you stated) the number of elements in each inner list are not same. With zip_longest() the missing elements are substituted with fillvalue, in this case -infinity (and -infinity will be always the lowest value in the max() function)
Try creating a dictionary keyed with the index of each sub list, then turning the values into the new list, then map to max:
from collections import defaultdict
elements = [[89, 213, 317], [106, 191, 314], [87]]
i_d = defaultdict(list)
for sub in elements:
for i, v in enumerate(sub):
i_d[i].append(v)
maxes = list(map(max, i_d.values()))
print(maxes)
i_d:
defaultdict(<class 'list'>, {0: [89, 106, 87], 1: [213, 191], 2: [317, 314]})
maxes:
[106, 213, 317]

strange output when returning the argument list [duplicate]

This question already has answers here:
Strange result when removing item from a list while iterating over it
(8 answers)
Closed 3 years ago.
Code
def removeEven(List):
for x in List:
if x % 2 == 0:
List.remove(x)
return List
print(removeEven([18, 106, -158, -124, 199, -28, -68, -91, 46, -190, 63, -30, 142, -36, -162, -121, 14, -192, -143, -57, -59, -129, -146, -76, -186, -84, 70, 19, -13, -12, -5, 179, -191, -43, 160, -156, 105, 104, 93, -188, -184, -197, -136, -35, 16]))
Output
[106, -124, 199, -68, -91, -190, 63, 142, -162, -121, -192, -143, -57, -59, -129, -76, -84, 19, -13, -5, 179, -191, -43, -156, 105, 93, -184, -197, -35]
Code
def removeEven(List):
result = []
for x in List:
if x % 2 != 0:
result.append(x)
return result
Output
[199, -91, 63, -121, -143, -57, -59, -129, 19, -13, -5, 179, -191, -43, 105, 93, -197, -35]
I came across this strange behavior. I am writing a simple function to remove even numbers from a list but when I modify the list that is passed as an argument and return it I get a weird output. Does anyone know what the reason is?
Please note i am not looking for answer to this problem it is easy to google but just explanation about why the output is different when i don't create a new list and return it.
One Liner in Python using list comprehension:
[x for x in li if x % 2 != 0]
strange output when returning the argument list
You are not permitted to remove elements from the list while iterating over it using a for loop. The best way to do this involves making a new list - either iterate over a copy, or construct a list with only the elements you want and assign it back to the same variable.
As we know, every item in a list lives at its own unique index; which are in order, starting from 0. If we remove an item, any item with an index greater than the one we've removed has now been shifted down.
And here's why that matters:
foo = ['a', 'b', 'c', 'd']
for index in range(len(foo)):
del foo[index]
In this loop, we're removing all the elements, so we should end up with foo == [], right? This is not the case. In our first trip through the loop, we remove the item at index 0, and the item at index 1 becomes the item at index 0. Our next time through the loop, we remove the item at index 1 which was previously the item at index 2.
See this to learn more on How to remove elements while iterating over a list. See this to learn more on How to remove elements while reverse iterating a list.

How to append two-dimensional python list without for loop?

Let's suppose that I have 3 python two-dimensional lists (data_1, data_2, data_3) of 10x5 dimensions. I want to make one list (all_data) from them with 30x5 dimensions. For now, I am doing this by applying the following:
data_1 = [[1, 2, 3, 4, 5], [6, 7, 8, 9, 10], ..., [46, 47, 48, 49, 50]]
data_2 = [[101, 102, 103, 104, 105], [106, 107, 108, 109, 110], ..., [146, 147, 148, 149, 150]]
data_3 = [[201, 202, 203, 204, 205], [206, 207, 208, 209, 210], ..., [246, 247, 248, 249, 250]]
all_data = []
for index, item in enumerate(data_1):
all_data.append(item)
for index, item in enumerate(data_2):
all_data.append(item)
for index, item in enumerate(data_3):
all_data.append(item)
If I simply do something like this:
all_data.append(data_1)
all_data.append(data_2)
all_data.append(data_3)
then I get a list of 3x10x5 which is not what I want.
So can I create a 30x5 list by appending three 10x5 lists without using any for loop?
You can just extend your list.
data = []
data.extend(d1)
data.extend(d2)
data.extend(d3)
Simply write:
all_data = data_1 + data_2 + data_3
If you want to merge all the corresponding sublists of these lists, you can write:
# function that merges all sublists in single list
def flatten(l):
return [el for subl in l for el in subl]
# zipped - is a list of tuples of corresponding items (our deep sublists) of all the lists
zipped = zip(data_1, data_3, data_3)
# merge tuples to get single list of rearranges sublists
all_data = flatten(zipped)
How about:
all_data = data_1 + data_2 + data_3
This should work:
data=[]
data[len(data):] = data1
data[len(data):] = data2
data[len(data):] = data3
In case you don't mind it being lazy, you could also do
import itertools
all_data = itertools.chain(data1, data2, data3)

Looping over a list and saving elements that meet a condition to a new list

I'm trying to loop over a list and save some elements to a new list: the ones that are at more than 50 greater than the previous value. My current code saves only the first value. I want [0, 76, 176, 262, 349].
list = [0, 76, 91, 99, 176, 192, 262, 290, 349]
new_list = []
for i in list:
if ((i+1)-i) > 50:
new_list.extend([i])
Solution
What I want is to save the values 0, 76, 176, 262, and 349.
So it sounds like you want to iterate over the list, and if the current element is greater than its preceding element by 50 then save it to the list and repeat. This solution assumes the original list is sorted. Let's turn this into some code.
lst = [0, 76, 91, 99, 176, 192, 262, 290, 349]
new_lst = []
for i, num in enumerate(lst):
if i == 0 or num - lst[i-1] > 50:
new_lst.append(num)
print(new_lst)
# [0, 76, 176, 262, 349]
The interesting part here is the conditional within the loop:
if i == 0 or num - lst[i-1] > 50:
The first part considers if we're at the first element, in which case I assume you want to add the element no matter what. Otherwise, get the difference between our current element and the previous element in the original list, and check if the difference is greater than 50. In both cases, we want to append the element to the list (hence the or).
Notes
You should avoid using list as a variable so you don't shadow the built-in Python type.
lst.extend([num]) is better written as lst.append(num).
enumerate(lst) allows you to easily get both the index and value of each element in a list (or any iterable).
The statement if ((i+1)-i) > 50 will always evaluate to if (1 > 50) which is false. You're looking for the next element in list, but i is simply the value of the current element. Try something like the tee() function in the itertools library to get multiple values, or something like
list = [0, 76, 91, 99, 176, 192, 262, 290, 349]
new_list = []
for i in range(len(list)):
print (i, list[i])
if i == 0 or (list[i] - list[i-1]) > 50:
new_list.append(list[i])
Keep in mind, I didn't add any checks for whether there is an i + 1 element, so you may need to do some error handling.
EDIT
This is my final edit. I would like to thank #Prune for enforcing standards :)
First, the code in PyCharm:
Second, the console output:
my solution
l = [0, 76, 91, 99, 176, 192, 262, 290, 349]
o = list(l[0]) + [a for a, b in zip(l[1:], l[:-1]) if a - b - 50 > 0]
output: [0, 76, 176, 262, 349]
for i in range(len(list)-1):
if (list[i+1]-list[i]) > 50:
new_list.append(list[i])
if list[-1] - new_list[-1] > 50:
new_list.append(list[-1]) #for the last element of list
Of course, the code can be made better. But this should work.
You can put a condition inside a list comprehension.
Also, do not give a variable the same name (list) as a built-in type.
my_list = [0, 76, 91, 99, 176, 192, 262, 290, 349]
# Start with the first element;
# then grab each element more than 50 greater than the previous one.
new_list = [my_list[0]]
new_list.extend([my_list[i] for i in range(1, len(my_list))
if my_list[i] - my_list[i-1] > 50])
print(new_list)
Output:
[0, 76, 176, 262, 349]

Categories

Resources