I have a list of dictionaries:
list = [{"id":2, "date": "2018-07-12"}]
Now I want to generate some nice output and have a function for it:
def generateOutput(myList):
outputList = []
for l in myList:
l['date_short'] = "Jul-12"
outputList.append(l)
return outputList
And here's where the desaster starts:
output = generateOutput(list)
output is fine but list that I need for further calculation and shouldn't have the date_short at all got a new key and is:
list = [ {"id":2, "date": "2018-07-12", "date_short": "Jul-12" }]
How to overcome this?
You are modifying the dictionaries in myList in-place. Instead, you probably want to copy them individually before adding new values to them. Try this:
def generateOutput(myList):
outputList = []
for l in myList:
output = l.copy()
output['date_short'] = "Jul-12"
outputList.append(output)
return outputList
Also, you should avoid naming a variable list since list is the name of a predefined type in Python.
Pass a copy of the variable to the function by using the copy module.
import copy
list = [{"id":2, "date": "2018-07-12"}]
def generateOutput(myList):
outputList = []
for l in myList:
l['date_short'] = "Jul-12"
outputList.append(l)
return outputList
generateOutput(copy.copy(list))
Related
What I want to get is
[a][b][c]
Getting each index from an array a=[a,b,c]. I’m using this to approach a value in dictionary.
All I could find was .append() but this returns me [a,b,c] not [a][b][c]
This is the function that I made
Def loop():
Newlist = []
for i in a:
Newlist.append(i)
return Newlist
You want to append a list of one value, not a single value. i.e.
>>> new_list = []
>>> new_list.append([1])
>>> new_list.append([2])
>>> new_list.append([3])
[[1], [2], [3]]
So in the method you'd do something like this:
def loop():
new_list = []
for i in a:
new_list.append([i])
return new_list
Try this:
Create a new list inside the loop that gets reset each time, add your variable, then add the new list to the parent list.
You can also grab individual lists from the parent list using the following: Newlist[1]
Def loop():
Newlist = []
for i in a:
temp_list = []
temp_list.append(I)
Newlist.append(temp_list)
return Newlist
I am trying to append an int value to a bunch of list variables all at once. Is there a for loop or such a function that would allow me to do that? Like I would like to append the val int to all list variables defined below.
val = 100
list_1=[]
list_2=[]
list_3=[]
list_4= []
Create a list containing all the lists, then use a loop:
val = 100
list_1 = []
list_2 = []
list_3 = []
list_4 = []
list_of_lists = [list_1, list_2, list_3, list_4]
for li in list_of_lists:
li.append(val)
Caution: do not be tempted to create list_of_lists in the following way:
list_of_lists = [[]] * 4
This will create a single list with 4 references to it, and changes done through 1 of them will be seen by all the other.
However, you can do
list_of_lists = [[] for _ in range(4)]
for li in list_of_lists:
li.append(100)
print(list_of_lists)
# [[100], [100], [100], [100]]
For something like this I would prefer a function to do so, as it is likely you'll do this again.
def appendAll(value, *args):
for listItem in args:
listItem.append(value)
This allows you to add a value to any set of lists. It doesn't require you to setup a list of variables as *args lets you pass any number of arguments and creates a tuple which lets us loop through each list and append our value to each list.
list1 = []
list2 = []
list3 = []
val = []
#now we can append val to all the lists or some of them
appendAll(val, list1, list2, list3)
I want to make one large list for entering into a database with values from 4 different lists. I want it to be like
[[list1[0], list2[0], list3[0], list4[0]], [list1[1], list2[1], list3[1], list4[1]], etc.....]
Another issue is that currently the data is received like this:
[ [ [list1[0], list1[1], [list1[3]]], [[list2[0]]], etc.....]
I've tried looping through each list using indexs and adding them to a new list based on those but it hasn't worked, I'm pretty sure it didn't work because some of the lists are different lengths (they're not meant to be but it's automated data so sometimes there's a mistake).
Anyone know what's the best way to go about this? Thanks.
First list can be constructed using zip function as follows (for 4 lists):
list1 = [1,2,3,4]
list2 = [5,6,7,8]
list3 = [9,10,11,12]
list4 = [13,14,15,16]
res = list(zip(list1,list2,list3,list4))
For arbitrtary number of lists stored in another list u can use *-notation to unpack outer list:
lists = [...]
res = list(zip(*lists))
To construct list of lists for zipping from you data in second issue use flatten concept to it and then zip:
def flatten(l):
res = []
for el in l:
if(isinstance(el, list)):
res += flatten(el)
else:
res.append(el)
return res
auto_data = [...]
res = list(zip(*[flatten(el) for el in auto_data]))
Some clarification at the end:
zip function construct results of the smallest length between all inputs, then you need to extend data in list comprehension in last code string to be one length to not lose some info.
So if I understand correctly, this is your input:
l = [[1.1,1.2,1.3,1.4],[2.1,2.2,2.3,2.4],[3.1,3.2,3.3,3.4],[4.1,4.2,4.3,4.4]]
and you would like to have this output
[[1.1,2.1,3.1,4.1],...]
If so, this could be done by using zip
zip(*l)
Make a for loop which only gives you the counter variable. Use that variable to index the lists. Make a temporary list , fill it up with the values from the other lists. Add that list to the final one. With this you will et the desired structure.
nestedlist = []
for counter in range(0,x):
temporarylist = []
temporarylist.append(firstlist[counter])
temporarylist.append(secondlist[counter])
temporarylist.append(thirdlist[counter])
temporarylist.append(fourthlist[counter])
nestedlist.append(temporarylist)
If all the 4 lists are the same length you can use this code to make it even nicer.
nestedlist = []
for counter in range(0,len(firstlist)): #changed line
temporarylist = []
temporarylist.append(firstlist[counter])
temporarylist.append(secondlist[counter])
temporarylist.append(thirdlist[counter])
temporarylist.append(fourthlist[counter])
nestedlist.append(temporarylist)
This comprehension should work, with a little help from zip:
mylist = [i for i in zip(list1, list2, list3, list4)]
But this assumes all the list are of the same length. If that's not the case (or you're not sure of that), you can "pad" them first, to be of same length.
def padlist(some_list, desired_length, pad_with):
while len(some_list) < desired_length:
some_list.append(pad_with)
return some_list
list_of_lists = [list1, list2, list3, list4]
maxlength = len(max(list_of_lists, key=len))
list_of_lists = [padlist(l, maxlength, 0) for l in list_of_lists]
And now do the above comprehension statement, works well in my testing of it
mylist = [i for i in zip(*list_of_lists)]
If the flatten concept doesn't work, try this out:
import numpy as np
myArray = np.array([[list1[0], list2[0], list3[0], list4[0]], [list1[1], list2[1], list3[1], list4[1]]])
np.hstack(myArray)
Also that one should work:
np.concatenate(myArray, axis=1)
Just for those who will search for the solution of this problem when lists are of the same length:
def flatten(lists):
results = []
for numbers in lists:
for output in numbers:
results.append(output)
return results
print(flatten(n))
I have a list of names my_names = ["A","B","C"]
I have a function that can takes each name from a list and returns several lists of information for that name.
def my_function(name):
return list1, list2, list3
For each name list1, list2, list3 are different.
I want to write a function that wouldn't need any user input but would return a list with 3 lists inside.
def my_function():
for name in my_list:
# Part I don't know how to do
name_list = list1, list2, list3
# A_list for "A", B_list for "B", C_list for "C"
return A_list, B_list, C_list
The only thin I don't know is how to make python introduce new empty lists depending on the name in my_list
A dictionary is best, but you can have a list of lists. Just make a main list: name_list = [] then append each list to it: name_list.append(list1), etc. Then reference each list using its index, then the elements in that list with a secondary index. For example,
def my_function():
for name in my_list:
name_list = []
name_list.append(list1)
name_list.append(list2)
name_list.append(list3)
return name_list
Then if you want to access the second element in the first list from the returned function, you would do so like:
name_list[0][1]
It's hard to say more without knowing more about your problem, but this will work, it's just not optimal.
You can create a nested list with n numbers of sublists, where n is any given number of lists
n = 3
nested_list = [[]] * n
# returns [[],[],[]]
#function that takes n, n=3
def create_nested_list(n):
nested_list = [[]] * n
return nested_list
nested list = create_nested_list(n)
You can append items in the nested list's lists by indexing, for instancce nested_list[0]=["A"] will append the number "A" to the first sublist, nested_list[1]=["B"]to the second and nested_list[2]=["C"] to the third sublist, so nested_list = [["A"],["B"],["C"]]
I'm iterating on a list and attempting to create sublists from its items. Every time I append to a variable, the value is added to every other variable that I have defined. I've stripped down the code substantially to illustrate.
item = 'things.separated.by.periods'.split('.')
list1 = list2 = []
i = item.pop(0)
print i
list1.append(i)
i = item.pop(0)
print i
list2.append(i)
print(item, list1, list2)
Returns:
things
separated
(['by', 'periods'], ['things', 'separated'], ['things', 'separated'])
What I expected:
things
separated
(['by', 'periods'], ['things'], ['separated'])
I think this might by answered here, but I'm not sure how to apply this fix to my circumstances. Thanks in advance!
The problem is the line
list1 = list2 = []
This makes list1 and list2 refer to the exact same list, so that if you append an item to one you also append it to the other. Change it to
list1 = []
list2 = []
list1 = list2 = []
You are setting list1 to be the exact same list as list2. Therefore, they basically mean the same thing.
To fix this, try something like this:
list1, list2 = [], []