I have a zipped list, with each tuple originally having the same length that looks like this:
[('MATH 441', 'GREAT, LOTS OF HOMEWORK, FUNNY'),(CSCI 519, 'AWFUL, BORING')...]
My goal is to split the second element of the tuple into individual elements based on the comma. From here, each tuple may have different lengths, therefore, I would like to check if the given tuple meets a specific length, and if it does not, enter an 'NAN' element into the tuple.
I imagine we must create a "lists of list", for tuples are immutable so this is what I have created thus far.
master = list(zip(course_codez, lst))
#to make it a list of list, not a list of tuples
master_two = [list(a) for a in zip(course_codez, lst)]
for i in master_two:
i[1].split(", ")
This is the thought process, but I am not entirely sure and would appreciate any help.
Thanks
split() doesn't (can't) modify the element in place, you need to assign the result back to the list element.
i[1] = i[1].split(", ")
You can do this directly in the list comprehension.
master_two = [(code, comment.split(", ")) for code, comment in zip(course_codez, lst)]
Related
I've created a list of objects each of which has an attribute which is a 5x5 numpy array with named columns and also an "ID" attribute. I want to create a function which checks if specific elements in the array (based on position) are in a (different) list of variable length, but exactly which array elements are being searched for can vary based on certain conditions.
Ideally I'd like to pass the list of subscripts used to retrieve the array elements as an argument to the function which will then attach each of the desired subscripts to the object and check for their presence in the list.
Here's what I mean:
# lst is the list we're checking against (i.e. are the array elements in this list)
# objs_list is the list of objects with the array and ID attributes
# "A" is the name of one of the columns in the numpy array
def check_list_membership(obj_id):
# create object_to_check which is a numpy array
object_to_check = next((x for x in objs_list if x.ID == obj_id)), None).arrayattribute
if (object_to_check["A"][0] in lst) & (object_to_check["A"][1] in lst) & \
(object_to_check["A"][2] in lst) & (object_to_check["A"][3] in lst ) & \
(object_to_check["A"][4] in lst):
print("all selected elements are in the list")
else:
print("one or more selected elements are not in the list")
In this example, I want to see if the array elements ["A"][0], ["A"][1], etc. are in the list. But in other cases I may want to check if ["A"][0], ["B"][1], and others are in the list. Obviously it's really clunky to have all of these conditional statements written out and I want to avoid this.
What I really want is to take the list of desired subscripts and attach each of them to the "object_to_check" in sequence and check for their membership in the list. I don't think string concatenation as described here will do what I want because I don't want the result to be strings. Instead I want each of these elements to be evaluated and checked for membership in the list. I don't think multiplying "object_to_check" to the length of the number of subscripts and zipping would help either because then I'd have to end up with strings (disembodied subscripts) and I'm not sure what I could do that would allow my list of object/subscript pairs to be evaluated (safely). I've looked into evaluating functions in string form which seems to be veering into controversial territory.
The desired function might look something like:
def check_list_membership(obj_id,list_of_subscripts):
object_to_check = next((x for x in objs_list if x.ID == obj_id)), None).arrayattribute
# pass 'list_of_subscripts' in here and attach to 'object_to_check'
if object_to_check[various subscripts] in lst:
print("all selected elements are in the list")
else:
print("one or more selected elements are not in the list")
How can I accomplish this without dozens of lines of hard-coding?
I have a empty list of tuple and I wish to enter values inside that tuple.
The desired output is :
lst = [()] --> lst = [(1,2,'string1','string2',3)]
A tuple is, by definition, unchangable.
You may want to replace that tuple with a new one like this:
lst = [()]
lst[0] = ("item1", "item2")
In this way you are replacing the origina tuple with a new one with the desired items. If the tuple is not empty you can do:
lst[0] = (*lst[0], "new item")
Here you are unpacking the values of the old tuple (*lst[0] is equal to "item1", "item2" in this example) and adding new items.
Note that if you are working with variable data maybe tuple is not the best data structure to use in this case.
you can't, A tuple is a collection that is ordered and immutable.
though, you can create a new tuple with the same name
I have list like mylist=['a','b','c',1,2,3]. iterating through each element of list, I wanna update this list as mylist=[['a',[]],['b',[]],['c',[]],[1,[]],[2,[]],[3,[]]]. the important thing is that each list associated with elements of mylist should not point to the same list. i.e., mylist[0][1] and mylist[1][1] should not point to the same list. So that i can modify each sub list independently. Hope my question is clear. Thanks in advance
This can be achieved easily using a list comprehension along your original myList. By adding an empty list on each iteration, there is no problem with sharing a reference to the same list, which you seem to be concerned about.
myList = [[element, []] for element in myList]
mylist=[[('The','d'),('apple','n'),('is','v'),('red','a')],[('I','p'),('feel','v'),('fine','adv')]]
This is a list of lists of tuples, and I wish to create a new list of tuples with information from another list added to it accordingly.
new_list=[['b','i','o','o'],['o','o','o']]
for each sub_list of these two lists, I have the exact same number of items as illustrated, and I wish to add the first string of the first list in new_list to the first tuple of the first list in my_list, the second string of the first list in new_list to second tuple of first list in my_list, and so on.
The ideal output looks like this
output=[[('The','d','b'),('apple','n','i'),('is','v','o'),('red','a','o')],[('I','p','o'),('feel','v','o'),('fine','adv','o')]]
I'd appreciate any suggestions, thank you!!
Basically this question has been answered elsewhere, so I flagged the question as duplicate, but assuming that you are new to python, here is a solution to your problem.
output = [[(*t,c) for t,c in zip(l1,l2)] for l1,l2 in zip(mylist,new_list)]
The new output is created using a list nested list comprehension (creating a list of lists). To match corresponding items from two lists together, you can use zip, which returns a generator of tuples of these corresponding items. The for loop that iterates through these tuples unpacks them into two separate items, i.e.
for l1,l2 in zip(mylist,newlist)
groups the sublists of mylist and newlist together, which the for are then unpacked into the lists l1 and l2 during the for iteration. Finally, as the items of the sublists of my_list are tuples, I unpack these tuples 'on the fly' while generating the new tuple: (*t,c) is the same as (t[0],t[1],c).
Please ask if anything stayed unclear.
Hope this helps.
I have two lists named queries_fetcher_list and reftable_column_name.
Now I need to perform the operation of taking an element from a and b, and make it as a tuple with zip().
This is the query for doing that:
some_list = []
for i in range (len(reftable_column_name)):
for row in queries_fetcher_list[i]:
some_list.append(dict(zip(reftable_column_name[i], row)))
Now I need that result to be append like this:
[[{first element}], [{second element}]]
What I need to do now is every time when a zip operation is performed that element has to append as a separate list, i.e. list inside a list, like this:
a = []
a = [['one'], ['two'], ['three']]
queries_fetcher_list contains a list of data that are retrived from an MySQL query retrieved with cursor.fetchall().
reftable_column_name is a list contains the column names of a table retrived with cursor.description().
some_list.append([dict(zip(reftable_column_name[i], row))])
will append single-element lists containing your dict.
define a list and everytime when elements got append into it free it, means empty it,now you can achieve what you want,eveytime when an element is appended into a list the list will be flushed and becomes an empty list but make sure to add your elements like this "list(your_element)".