excluding lists that have more than one x - python

I have a bunch of lists that look something like this:
my_list = [x, y, z, x, z, w]
I want to exclude lists that have more than one 'x', however one 'x' is allowed, as well as repeats of other letters.
I'm not quite sure where to start with this...

You can find the number of list items equal to x by
my_list.count(x)
To filter a list of lists for only the lists that contain up to one x, use
[lst for lst in list_of_lists if lst.count(x) <= 1]

Use collections.Counter to count the number of 'x's.

The count() method will return the number of times a certain element appeared in the list, e.g.:
list.count(x)
So you can do something like
if list.count(x) <= 1:

Related

How to iterate a zip list and print each index of it after joining to lists of the same size?

Given the variables:
X = ['a', 'b', 'c']
Y = [1, 2, 3]
complete the following statement:
[print(pair) for pair in ...]
so as to print to the screen pairs of elements from X and Y which occupy the same position in the index.
I know I can make a join X and Y and make a list using list(zip(X,Y)) but the adding that in the statement gives an empty list.
I can't solve this problem using the form required any help?
thanks!
Not really clear what you're trying to achieve. If you need to print pairs, zip works, i.e.
for pair in zip(X, Y):
print(pair)
[print(pair) for pair in ...] is list comprehension, this is made to create lists, not to print data:
pairs_list = [pair for pair in zip(X, Y)] # don't do this
which is simply pairs_list = list(zip(X, Y)). Does this make sense to you?
Using list comprehensions to leverage a sideeffect (like printing something) is frowned upon. If you dont need a list, don't build one.
[print(pair) for pair in zip(X,Y)] # no need to list(zip(...))
will result in lots on None ... because the return value of print() is None.
Use a simple loop:
for p in zip(X,Y):
print(p)

Getting intersection of lists, beginning with the same string

I am searching for elements in one list that begin with the elements in the second list
lis = [x for x in LL if any(x.startswith(i) for i in RR)]
This gives me the correct results, however i need to get a list containing the strings from both the LL and RR lists (preferably in a tuple).
(if this sounds odd, because one might think that they would look the same, in this case they do not)
This only gives me the results from list LL
Any suggestions on how to get the results from LL accompanied by the match that was found in RR ?
Try this out
from itertools import product
lis = [(x, y) for x, y in product(LL, RR) if x.startswith(y)]
You can do this:
lis = [(x,i) for x in LL for i in RR if (x.startswith(i))]

compactly generate list of list python

I have to create a list of lists (each inner list has n fixed elements). Right now, for n=3 I am doing this:
my_list = []
for x in range(min_inner max_inner + 1):
for y in range(min_outer, max_outer + 1):
for z in range(fixed_param):
my_list.append([x, y, z])
When I tried list comprehension, something like:
[[x,y,z] for x in range(1,4), y in range(1,4), z in range (4)]
I get a name error
NameError: name 'z' is not defined
Is there a list comprehension way of doing that? Considering that n can be any number (though not necessarily arbitrarily large)
You need to loop over your range objects inside the list comprehension too.
[[x,y,z] for x in range(1,4) for y in range(1,4) for z in range (4)]
Also as a more concise way you could use itertools.product() to achieve the same result:
from itertools import product
list(product(range(1,4),range(1,4),range(4)))
Note that itertools.product() returns an iterator object which is pretty more optimized (in terms of memory usage) than list comprehension which returns a list. And if you just want to iterate over the result you don't need to convert the result to list. Otherwise the list comprehension will performs faster.

Check if there are 2 or 3 elements with same value in a list/tuple/etc.

I have a 5-element list and I want to know if there are 2 or 3 equal elements (or two equal and three equal). This "check" would be a part of if condition. Let's say I'm too lazy or stupid to write:
if (a==b and c==d and c==e) or .......... or .........
i know it might be written like this, but not exactly how:
if (a==b and (c==b and (c==e or ....
How do I do it? I also know that you can write something similar to this:
if (x,y for x in [5element list] for y in [5element list] x==y, x not y:
If you just want to check for multiple occurences and the objects are of an hashable type, the following solution could work for you.
You could create a list of your objects
>>>l = [a, b, c, d, e]
Then, you could create a set from the same list and compare the length of the list and the length of the set. If the set has less elements than the list, you know you must have multiple occurences.
>>>if (len(set(l)) < len(l)):
...
Use count. You just want [i for i in myList if myList.count(i) > 1]. This list contains the repeated elements, if it's non-empty you have repeated elements.
Edit: SQL != python, removed 'where', also this'll get slow for bigger lists, but for 5 elements it'll be fine.
You can use collections.Counter, which counts the occurrence of every element in your list.
Once you have the count, just check that your wanted values (2 or 3) are present among the counts.
from collections import Counter
my_data = ['a', 'b', 'a', 'c', 'd']
c=Counter(my_data)
counts = set(c.values())
print 2 in counts or 3 in counts

Unpacking an unspecified amount of variables

So I have a list of tuples. Each tuple in the list will be the same length, but tuple size will vary based on list. For example, one list could contain tuples of length 4, another could contain tuples of length 5. I want to unpack each individual value of a tuple, and use each value to multiply it by an element in another list. For example(with a list of tuples of length 3):
somelist = [a,b,c]
tuplelist = [(2,3,5),(5,7,5),(9,2,4)]
listMult = []
for x,y,z in tuplelist:
listMult.append([somelist[0]*x,somelist[1]*y,somelist[2]*z])
The problem with this is that it won't scale if I'm using another list with tuples of a different size.
If you don't know how many elements each tuple has, unpacking would be a bad idea. In your example, you would instead do the following:
listMult = [sum(x*y for x, y in zip(tup, somelist)) for tup in tuplelist]
In general, you'd try to use iteration, starargs, and other things that operate on an iterable directly instead of unpacking.
As presented, the question is incompletely specified. But there is an interesting and useful variant of the question, "How do I unpack a fixed number of elements from tuples of an unknown length?".
The answer to that might be useful to you:
tuple_list = [(2,3), (5,7,5), (9,2,4,2)]
pad_tuple = (0, 0, 0)
for t in tuple_list:
t += pad_tuple # make sure the tuple is sufficiently long
x, y, z = t[:3] # only extract the first three elements
print(x,y,z)

Categories

Resources