Printing elements of a set in python [duplicate] - python

This question already has answers here:
Converting a list to a set changes element order
(16 answers)
Closed 4 years ago.
I want to print the elements of the set consecutively, so I wrote the following code:
s='dmfgd'
print(set(s))
However, this code shows the output as:
set(['m', 'd', 'g', 'f'])
but, I want output like:
set(['d','m','f','g'])
Any help will be appreciated.

Set is unordered. You can instead use a list of dict keys to emulate an ordered set if you're using Python 3.6+:
print(list(dict.fromkeys(s)))
This outputs:
['d', 'm', 'f', 'g']

Python set is unordered collections of unique elements
Try:
s='dmfgd'
def removeDups(s):
res = []
for i in s:
if i not in res:
res.append(i)
return res
print(removeDups(s))
Output:
['d', 'm', 'f', 'g']

Related

Python : Comprehensions [duplicate]

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)

Check for similarities in multiple lists and return match/ [duplicate]

This question already has answers here:
Python -Intersection of multiple lists?
(6 answers)
Closed 3 years ago.
I have four lists with strings:
a = ['A', 'B', 'GG', 'Z']
b = ['A', 'F', 'GG', 'Z']
c = ['A', 'P', 'E', 'Z']
d = ['A', 'T', 'R', 'Z']
and I want to return a single list that has the string that appears in all lists to get:
final_list = ['A', 'Z']
I know you can use set and intersection but these use at most one argument whilst I have four. Is there another way of doing this?
Thank you.
EDIT
I tried:
final_list = set(a).intersection(b,c,d)
Does it matter which order the lists are placed?
Using a list comprehension along with zip with an equality check:
[chars[0] for chars in zip(a,b,c,d) if len(set(chars)) <= 1]

How to create a new sublist from a list whose length depends on another list [duplicate]

This question already has answers here:
Splitting a string by list of indices
(4 answers)
Closed 4 years ago.
I would like to create a new list with sub-lists inside whose length depends on another list, for example I have:
a = [1,3,2,5,4]
b = ['a','b','c','d','e','f','g','h','i','l','m','n','o','p','q']
and I would like to have a nested list of the form:
[['a'],
['b', 'c', 'd'],
['e', 'f'],
['g', 'h', 'i', 'l', 'm'],
['n', 'o', 'p', 'q']]
Steps to solve this:
create an empty list
create a int done=0 that tells you how many things you already sliced from your data
loop over all elements of your "how to cut the other list in parts"-list
slice from done to done + whatever the current element of your "how to cut the other list in parts" is and append it to the empty list
increment done by whatever you just sliced
add the (if needed) remainder of your data
print it.
Doku:
Understanding Python's slice notation
How to "properly" print a list?
and infos about looping here: looping techniques PyTut
You can read about why we do not solve your homework for you here: open letter to students with homework problems
a = [1,3,2,5,4]
b = ['a','b','c','d','e','f','g','h','i','l','m','n','o','p','q']
out=[]
for number in a:
out.append(b[:number])
b=b[number:]
print(out)
#[['a'], ['b', 'c', 'd'], ['e', 'f'], ['g', 'h', 'i', 'l', 'm'], ['n', 'o', 'p', 'q']]
Description
The out is the final output list. The loop iterates through each element in list a (say 'number') and appends a list of that many elements from the start of list b to our output list. Then it proceeds to update list b so that those elements are removed.

Combination of list of list elements [duplicate]

This question already has answers here:
How to get the cartesian product of multiple lists
(17 answers)
How to concatenate (join) items in a list to a single string
(11 answers)
Closed 4 years ago.
I want a list which is a combination of list of list elements
For example:
my input
x = [['P'], ['E', 'C'], ['E', 'P', 'C']]
The output should be
['PEE','PEP','PEC','PCE','PCP','PCC']]
Any help is highly appreciated.
Use itertools
[''.join(i) for i in itertools.product(*x)]
Note: assuming that last one should be 'PCC'
here is a solution
def comb(character_list_list):
res = ['']
for character_list in character_list_list:
res = [s+c for s in res for c in character_list]
return res
On your example, it gives, as expected
>>> comb([['P'], ['E', 'C'], ['E', 'P', 'C']])
['PEE', 'PEP', 'PEC', 'PCE', 'PCP', 'PCC']
A shorter version is possible using functools.reduce(), but the use of this function is not recommanded.

How to combine every element of a list to the other list? [duplicate]

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

Categories