I have a creative problem that I want to solve.
Let's say if I have two list as below. I want to compare if all elements in the req_param list are also in the full_list. I know it is easy to do the same using a for loop and getting the answer. But I am trying to figure out if there is a python3 in-built fxn to do the same..
req_param = ['ele1','ele2','ele3','ele4]
full_param = [['ele1','ele2','ele3','ele4','ele6']
During the comparison, I don't care if there are additional elements in full_param list. I just care that if full_param has all the elements of the req_param, then somehow I want to return it true else, I want to return it false.
Currently, this works with the for loop. But really think there should be an inbuilt fxn like compare. The most important part is that each element may not come in the same order, so I am ok to sort my list before passing it to a fxn...
As was mentioned there are several ways:
Use all(): if all(item in full_list for item in req_param):
Use set(): if set(req_param).issubset(set(full_param)):
I figured out a different way you can solve the problem.
You could just use set() and len() to solve the problem instead of for loop
Here's how:
r = ['ele1','ele2','ele3','ele4']
f = ['ele1','ele2','ele3','ele4','ele6']
print(len(set(r)-set(f))==0)
use all keyword , it returns True if all the conditions are satisfied else it returns False
Related
I have a function which returns a tuple of two lists ( E.G return (["a", "b"], ["c"]) ).
I'm trying to append the two returned lists into two different lists.
I could do something like:
temp1, temp2 = functionCall()
list1.append(temp1)
list2.append(temp2)
But I'm trying to find some more elegant solution without temporary variables.
Some things I tried are using for loops and lambdas but couldn't find a satisfying solution.
I'm probably missing something obvious since I'm pretty inexperienced.
Can someone help me?
Would it be possible to change the function signature and send in the top level lists as arguments and retrieve the final appended lists out directly?
Something like:
functionCall(list1, list2)
edit: explain and format
This += with list1 is actually a function call to extend for you
list1 += functionCall()
list2.append(list1.pop())
I've just learned of list comprehension but I can't quite get it to work in the right context.
my for loop is:
results and instances are lists
for i in results:
instances.remove(i)
results.remove(i)
I tried [i for i in one if one.count(i)<2 if two.count(i)<2] but it doesn't work. I can get it to work on just one of them with this, [i for i in one if one.count(i)<2], but I wanted to incorporate both of them into the same loop. Can someone show me the easiest way to go about this?
Assuming results is a list. You seem to be trying to do this
for i in results:
instances.remove(i)
del results[:]
list comprehension is the wrong thing to use here. You're not trying to create a new list from a sequence.
This loops is similar, but will remove the instances in the reverse order
while results:
instances.remove(results.pop())
You need to first take the results out of the for loop. Set it after it and then delete it once the for loop has finished.
My problem is, that need a list with length of 6:
list=[[],[],[],[],[],[]]
Ok, that's not difficult. Next I'm going to insert integers into the list:
list=[[60],[47],[0],[47],[],[]]
Here comes the real problem: How can I now extend the lists and fill them again and so on, so that it looks something like that:
list=[[60,47,13],[47,13,8],[1,3,1],[13,8,5],[],[]]
I can't find a solution, because at the beginning i do not know the length of each list, I know, they are all the same, but I'm not able to say what length exactly they will have at the end, so I'm forced to add an element to each of these lists, but for some reason i can't.
Btw: This is not a homework, it's part of a private project :)
You don't. You use normal list operations to add elements.
L[0].append(47)
Don't use the name list for your variable it conflicts with the built-in function list()
my_list = [[],[],[],[],[],[]]
my_list[0].append(60)
my_list[1].append(47)
my_list[2].append(0)
my_list[3].append(47)
print my_list # prints [[60],[47],[0],[47],[],[]]
I have a list of lists, and will do a search on it which will yield just one result. The following code works but isn't intuitive because it doesn't really express the intent of what I'm trying to do... it looks like I'm trying to return a list, and just happen to want to return the first item in the last: which isn't true, as I always will want just one item, never a list. Anything more intuitive here?
game = [g for g in games if g.num==5 and re.search("ucla", g.a_name, re.I)][0]
Sadly, there isn't a built-in method in Python for searching in a list using a helper function.
However, you can use a generator expression and make it stop on first match instead on iterating over the remaining list even if a match is already found.
game = next(g for g in games if g.num==5 and re.search("ucla", g.a_name, re.I))
Or maybe more functional approach (this is not equivalent to the previous one on Python 2.x, because it generates the whole list, and doesn't stop at the first matching element. On Python 3.x filter returns an iterator and behavior is same).
game = next(filter(lambda g: g.num==5 and re.search("ucla", g.a_name, re.I), games))
It's a matter of preference whether the filter is clearer or not. BDFL prefers comprehension tho.
list_games = [g for g in games if g.num==5 and re.search("ucla", g.a_name, re.I)]
game = list_games[0]
You can explicitly assign the first element of that list to your variable game. That makes it a bit clearer.
I have admittedly not done a huge amount of research on this topic, but I am trying to get something done quickly. I have a dictionary with integers as keys and lists as values. Previously, I was checking for a list being in the dictionary with a simple if statement:
if(someList is in someDictionary.values()):
someCode() #failure
However, I realized it is incorrect for what I was doing, and I only want to check for the inclusion of the first value of the list in the dictionary's values, e.g
if(someList[0] == someValueInDictionary[0]):
someCode() #failure
I first tried
if(someList[0] is in someDictionary.values()[0]):
someCode() #failure
But that clearly doesn't work. As someDictionary.values() is a list in itself. I realize I could iterate through all of the values to check, e.g
for list in someDictionary.values():
if(someList[0] == list[0]):
someCode() #failure
actualCode() #success
But this really messes up the flow of my program. I am a new Python programmer, most experienced in Java, and I am trying to get the conciseness and convenience of Python in my bones, as such I thought there might be a better solution for what I am testing for. If there is not, I can make the iteration thing work, but if there is, I would greatly appreciate it!
Thanks in advance!
Use the any() function with a generator expression to find if there is any dictionary value that contains your item:
if any(someList[0] in v for v in someDictionary.itervalues()):
# item found
Use someDictionary.values() on Python 3. The generator expression loops over the dictionary values (without producing a list of all values first) and tests against each value, one by one as the generator expression is iterated over.
any() only tests elements from the generator expression until one is True, and then stops looping, making this relatively efficient.
If you need to have the key of the matching value, use next():
next((k for k, v in someDictionary.iteritems() if someList[0] in v), None)
which returns either the matching key, or None in no match is found.
Try this, assuming that you want to check the first element of someList against the first element in all of someDictionary's list values (the code in the question seems to indicate that's what you want):
if someList[0] in (x[0] for x in someDictionary.itervalues()):
someCode()
But if what you want is to check if the first element of someList is in any of the lists of values, then try this:
import itertools as it
if someList[0] in it.chain(*someDictionary.itervalues()):
someCode()