Introducing new variables using a given string - python

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"]]

Related

How to return all item in list of lists that are not in other list of lists in Python?

I have 2 list of lists:
list1: [[1,2,3],[2,5],[6,7,4]]
list2: [[1,3],[2],[6,4],[9,0,3]]
I want to do few things:
Find every number that is in list 1 but is not in list 2, store it in a new list, and then append this new list to list2.
In our case: new_list = [5,7]
and then, we will add it to list2 = [[1,3],[2],[6,4],[9,0,3],[5,7]]
Then, I want to remove duplicates of numbers from each list1 and list 2:
In our case: list1 = [[1,3],[2,5],[6,7,4]], list2 = [[1],[2],[6,4],[9,0,3],[5,7]]
I have an implementation using For loops, but I need something more elegant for that.
Can you help me please find out a way?
Using Python, you can do the first part with a set comprehension:
list2.append(list({i for j in list1 for i in j}.difference({i for j in list2 for i in j})))

Appending int value to a bunch of list variables

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)

python apply a function after checking if variable is single list or list of lists

I intend to apply a function to a variable. I do not know beforehand if the incoming variable will be a list of list or a single list. e.g
var_name = [a, b, c]
or
var_name = [[a,b,c], [d,e,f], [h,i,j]]
The list of list could contain as many lists as possible. How do I go about verifying if the variable is a list or list of lists. I intend to apply a function depending on the type. I tried to use len(var_name) but the length for list will be the number of items in single list while for list of lists, it is the number of lists in the list of lists.
what I am trying to achieve is this:
#function for list
def apply_val(lst):
do something with single list
#function for list of list
def apply_val2(lst):
do something with list of lists
var_name = single_list or list_of_lists
if var_name == single list
apply_val(single_list)
else:
apply_val(list_of_lists)
How do I check if the var_name is a list or list of lists?
list of lists does not mean anything, what is [["foo", "bar"], "baz"] ?
However, if you are sure you could only have "list of something that is not a list" and "list of list", just:
Check the list is not empty
Then, check the type of first item
if len(my_list) > 0:
if isinstance(my_list[0], list):
# List of list
pass
else:
# Simple list
pass
if the single list is always just values AND the list of lists always contains ONLY lists, you can check if it is a single list or list of lists like so:
list1 = [1,2,3]
list2 = [[1,2,3],[1,2,3]]
if type(list2[0]) == list:
print('list of lists')
else:
print('single list')
returns 'list of lists' for list2 and 'single list' for list1
if there is a mix you could do something like:
list3 = [1,[1,2,3], 4.343, 'string']
types = set([type(element) for element in list3])
if list in types and len(types) > 1:
print('mixed')
Try this
def check_list(test_list):
if type(test_list[0]) == list:
return True
else:
return False

How to merge n lists together item by item for each list

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))

Exclude items from list of lists Python

I have the next list of
testList = []
testList.append([0,-10])
testList.append([-12,122])
testList.append([13,172])
testList.append([17,296])
testList.append([-10,80])
testList.append([-16,230])
testList.append([-18, 296])
testList.append([-2, -8])
testList.append([-5,10])
testList.append([2,-4])
and another lists which contains elements from previous list:
m1 = []
m1.append([0, -10])
m1.append([13, 172])
Then I try to get a subarray from the list testList with the next statement:
[element for i, element in enumerate(testList) if i not in m1]
But I get the same list as testList.
How can I achieve this?
If you don't care about the order in the lists, you can use sets instead:
# result will be a set, not a list
not_in_testlist = set(testlist) - set(m1)
If you want the result to be a list again:
# result will be a list with a new order
not_in_m1 = list(set(testlist) - set(m1))
Be aware that using sets will lose the order of the original lists because sets are unordered types (they use hashing under the hood).
If you need to preserve the order, then Andrew Allaire's answer is correct:
# result is a list, order is preserved
not_in_testlist = [e for e in testlist if e not in m1]
The problem is with your use of enumerate. The i is just going to be an integer, and therefor never in a list that only has lists in it. Try this:
[element for element in testList if element not in m1]
Try with this:
def clean_list(my_list, exclusion_list):
new_list = []
for i in my_list:
if i in exclusion_list:
continue
else:
new_list.append(i)
return new_list

Categories