This question already has answers here:
How to get ordered set? [duplicate]
(2 answers)
Closed 1 year ago.
I have a list :
lis = ['a', 'b', 'c', 'd', 'd', 'e', 'e']
I am trying to use comprehensions to get values which are duplicate.
duplicates = set([x for x in lis if lis.count(x) > 1])
This returns :
{'d','e'}
Now I create a list out of above set :
duplicates = list(set([x for x in lis if lis.count(x) > 1]))
I get output as :
['e', 'd']
Why the order changes?
set does not guarantee the order, dict does.
>> duplicates = dict.fromkeys([x for x in lis if lis.count(x) > 1], None)
>> duplicates = list(duplicates); duplicates
['d', 'e']
That's because Set stores the elements in a random manner.
Try running this code multiple times and see the outputs.
s = {"a","b","g","f"}
print(s)
Related
This question already has answers here:
How do I find the duplicates in a list and create another list with them?
(42 answers)
Closed 5 months ago.
>>> list_a = ['a', 'b', 'c', 'c']
>>> get_repeated(list_a)
['c']
What would be the most pythonic way to do function get_repeated()?
this should work
from collections import Counter
list_a = ['a', 'b', 'c', 'c']
count = Counter(list_a)
output = [key for key, val in count.items() if val > 1]
print(output)
>>> ['c']
This question already has answers here:
Get key by value in dictionary
(43 answers)
How to implement an efficient bidirectional hash table?
(8 answers)
Python: How to search a nested list using recursion
(5 answers)
Closed 8 months ago.
Let's say I have:
ref = ['<var>', '<id>', '<expr>']
val = [['a', 'b', 'c'], 'a', '1+1']
dicio = dict(zip(ref, val))
now, I know that by doing
list(dicio.keys())[list(dicio.values()).index('a')]
It returns <id>. But let's say that you only had one value associated per key, so
val = [['a', 'b', 'c'], 'b', '1+1']
How could I get <var> without listing ['a', 'b', 'c']?
Thank you.
Just replace "a" value by the list ['a', 'b', 'c']:
print(list(dicio.keys())[list(dicio.values()).index(['a', 'b', 'c'])])
You will get as output the value associated with the index you inserted before:
<var>
Or you can use list comprehension to traverse the list of dict values:
ref = ['<var>', '<id>', '<expr>']
val = [['a', 'b', 'c'], 'a', '1+1']
dicio = dict(zip(ref, val))
selectedVal = list(i for i in list(dicio.values()) if "a" in i)[0]
print(list(dicio.keys())[val.index(selectedVal)])
Which outputs the same as the previous solution.
This question already has answers here:
How to get all subsets of a set? (powerset)
(32 answers)
Closed 1 year ago.
I am not sure of the technical terminology for what I am trying to do, but this is the gist of it. I have the following list:
x = ['a', 'b', 'c']
I want to create a new list y where len(y) = 2 ** len(x) such that:
y = ['∅', 'a', 'b', 'c', 'a,b', 'a,c', 'b,c', 'a,b,c']
I am unsure of what operations to use when looping through x to create the desired list y.
Although this is much less efficient than itertools, if you are not allowed to use libraries, you could make a recursive function to produce the power-set and assemble the strings using join() in a list comprehension:
def powerSet(L):
return [[]] if not L else [c for p in powerSet(L[1:]) for c in (p,L[:1]+p)]
x = ['a','b','c']
y = [",".join(s) or "ø" for s in powerSet(x)]
print(y)
['ø', 'a', 'b', 'a,b', 'c', 'a,c', 'b,c', 'a,b,c']
You can also do this directly in an iterative function that extends all previous combinations with each letter in the list:
def allCombos(L):
result = [""]
for c in L:
result.extend([f"{r},{c}" if r else c for r in result])
result[0] = "ø"
return result
print(allCombos(x))
['ø', 'a', 'b', 'a,b', 'c', 'a,c', 'b,c', 'a,b,c']
This question already has answers here:
Python list sort in descending order
(6 answers)
Sort Python list using multiple keys
(6 answers)
Closed 4 years ago.
I have been trying to sort a list of elements (string) according to their occurrence in Python3. I have been using the inbuilt sort() method with the string.count as key as shown below.
p = "acaabbcabac"
print(sorted(p, key=p.count))
# Output : ['c', 'b', 'b', 'c', 'b', 'c', 'a', 'a', 'a', 'a', 'a']
#But expected output is ['a','a','a','a','a','b','b','b','c','c','c']
p = "acaabbcb"
print(sorted(p, key=p.count))
# Output : ['c', 'c', 'a', 'a', 'a', 'b', 'b', 'b']
#Output is as expected
p = "ababab"
print(sorted(p, key=p.count))
# Output :['a', 'b', 'a', 'b', 'a', 'b', 'a', 'b']
#But expected output is ['a','a','a','b','b','b']
What I have observed is, the above sort works as per the occurrence of the element, but it works only if the counts of each element is different. If the occurrence of any two or more elements is same, then they are listed in the same order they appear in the string/list.
Am I doing something wrong or is there a better approach at this ? I tried searching answers for this issue but I could not find and so am posting this here.
Thanks in advance.
Use a lambda function in your sorting key, where the first operation is p.count, and the second simply sorts on the element value (which ends up being alphabetical):
p = "ababab"
sorted(p, key = lambda x: [p.count, x])
# ['a', 'a', 'a', 'b', 'b', 'b']
This question already has answers here:
Element-wise addition of 2 lists?
(17 answers)
Closed 5 years ago.
Suppose there are two lists:
['a', 'b', 'c'], ['d', 'e', 'f']
what I want is:
'ad','ae','af','bd','be','bf','cd','ce','cf'
How can I get this without recursion or list comprehension? I mean only use loops, using python?
The itertools module implements a lot of loop-like things:
combined = []
for pair in itertools.product(['a', 'b', 'c'], ['d', 'e', 'f']):
combined.append(''.join(pair))
While iterating through the elements in the first array, you should iterate all of the elements in the second array and push the combined result into the new list.
first_list = ['a', 'b', 'c']
second_list = ['d', 'e', 'f']
combined_list = []
for i in first_list:
for j in second_list:
combined_list.append(i + j)
print(combined_list)
This concept is called a Cartesian product, and the stdlib itertools.product will build one for you - the only problem is it will give you tuples like ('a', 'd') instead of strings, but you can just pass them through join for the result you want:
from itertools import product
print(*map(''.join, product (['a','b,'c'],['d','e','f']))