Creating a new list from a list of tuples in python - python-3.x

I have a list of tuples
a = [(1,'a'),(2,'b'),(3,'c'),(4,'d')]
and another list
b = [1,2,4]
Now, using lists a and b I want to generate a list c which contains the corresponding elements of a which are present in list b.
That means c should be
c = ['a','b','d']
how can I do that?

Nested loops:
c = []
for b_number in b:
for a_number, a_letter in a:
if b_number == a_number:
c.append(a_letter)
break
or a less efficient (no break) list comprehension:
c = [a_letter for a_number, a_letter in a for b_number in b if b_number == a_number]
Assuming the numbers in a are unique it will be easier to use a dictionary:
a = {1: 'a', 2: 'b', 3: 'c', 4: 'd'}
b = [1, 2, 4]
c = [a[b_number] for b_number in b]

Related

How do I use python to turn two lists into a dictionary, and the value is the maximum value

I have two lists here
L = ["a","b","b","c","c","c"]
L_02 = [1,3,2,4,6,""]
I want to turn two lists into a dictionary, and the value is the maximum value
dic = {"a":1,"b":3,"c":6}
how can I do this?
We can first get the indices of each element in the list, get the corresponding values in the second list, and find the maximums and make a dictionary.
dic = {}
for element in set(L):
indices = [i for i, x in enumerate(L) if x == element]
corresponding = []
for i in indices:
if type(L_02[i]) == int:
corresponding.append(L_02[i])
value = max(corresponding)
dic[element] = value
L = ["a","b","b","c","c","c"]
L_02 = [1,3,2,4,6,""]
return_dict = {}
for item1, item2 in list(zip(L,L_02)):
if item1 not in return_dict:
return_dict[item1] = item2
elif isinstance(item2,int) and return_dict[item1] < item2:
return_dict[item1] = item2
print(return_dict)
Output:
{'a': 1, 'b': 3, 'c': 6}

appending a string to a list of strings if the string in the list is equal to some variable in python

a=['item1', 'item2', 'item3', ...]
b='item2'
now if I want to say add * to the beginning and end of 'item2' in the list 'a' how can i do that?
You could use a list comprehension:
>>> a = ['item1', 'item2', 'item3']
>>> b = 'item2'
>>> c = [f'*{s}*' if s == b else s for s in a]
>>> c
['item1', '*item2*', 'item3']

Make a list with non-decreasing order elements of a list in Python

I have a list a = [2,2,1,3,4,1] .
I want to make a new list c with the non-decreasing elements lists of list a.
That means my expected form is -
c = [[2,2],[1,3,4],[1]]
Here is my code:
>>> c = []
>>> for x in a:
... xx = a[0]
... if xx > x:
... b = a[:x]
... c.append(b)
... a = a[x:]
but my output is:
>>> c
[[2], [2]]
How can i make a list with all non-decreasing part of list a?
You can initialise the first entry of c with [a[0]] and then either append the current value from a to the end of the current list in c if it is >= the previous value, otherwise append a new list containing that value to c:
a = [2,2,1,3,4,1]
c = [[a[0]]]
last = a[0]
for x in a[1:]:
if x >= last:
c[-1].append(x)
else:
c.append([x])
last = x
print(c)
Output:
[[2, 2], [1, 3, 4], [1]]
If I understand what you are after correctly then what you want is to split the list every time the number decreases. If so then this should do what you need
c = []
previous_element = a[0]
sub_list = [previous_element]
for element in a[1:]:
if previous_element > element:
c.append(sub_list)
sub_list = []
previous_element = element
sub_list.append(previous_element)
c.append(sub_list)
Output:
In [1]: c
Out[2]: [[2, 2], [1, 3, 4], [1]]
There is possibly a clearer way to right the above, but it's pre coffee for me ;)
Also note that this code assumes that a will contain at least one item, if that is not always the case then you will need to either add an if statement around this, or re-structure the loop in a more while loop

return dictionary of file names as keys and word lists with words unique to file as values

I am trying to write a function to extract only words unique to each key and list them in a dictionary output like {"key1": "unique words", "key2": "unique words", ... }. I start out with a dictionary. To test with I created a simple dictionary:
d = {1:["one", "two", "three"], 2:["two", "four",
"five"], 3:["one","four", "six"]}
My output should be:
{1:"three",
2:"five",
3:"six"}
I am thinking maybe split in to separate lists
def return_unique(dct):
Klist = list(dct.keys())
Vlist = list(dct.values())
aList = []
for i in range(len(Vlist)):
for j in Vlist[i]:
if
What I'm stuck on is how do I tell Python to do this: if Vlist[i][j] is not in the rest of Vlist then aList.append(Vlist[i][j]).
Thank you.
You can try something like this:
def return_unique(data):
all_values = []
for i in data.values(): # Get all values
all_values = all_values + i
unique_values = set([x for x in all_values if all_values.count(x) == 1]) # Values which are not duplicated
for key, value in data.items(): # For Python 3.x ( For Python 2.x -> data.iteritems())
for item in value: # Comparing values of two lists
for item1 in unique_values:
if item == item1:
data[key] = item
return data
d = {1:["one", "two", "three"], 2:["two", "four", "five"], 3:["one","four", "six"]}
print (return_unique(d))
result >> {1: 'three', 2: 'five', 3: 'six'}
Since a key may have more than one unique word associated with it, it makes sense for the values in the new dictionary to be a container type object to hold the unique words.
The set difference operator returns the difference between 2 sets:
>>> a = set([1, 2, 3])
>>> b = set([2, 4, 6])
>>> a - b
{1, 3}
We can use this to get the values unique to each key. Packaging these into a simple function yields:
def unique_words_dict(data):
res = {}
values = []
for k in data:
for g in data:
if g != k:
values += data[g]
res[k] = set(data[k]) - set(values)
values = []
return res
>>> d = {1:["one", "two", "three"],
2:["two", "four", "five"],
3:["one","four", "six"]}
>>> unique_words_dict(d)
{1: {'three'}, 2: {'five'}, 3: {'six'}}
If you only had to do this once, then you might be interested in the less efficeint but more consice dictionary comprehension:
>>> from functools import reduce
>>> {k: set(d[k]) - set(reduce(lambda a, b: a+b, [d[g] for g in d if g!=k], [])) for k in d}
{1: {'three'}, 2: {'five'}, 3: {'six'}}

Compare unique string values between two lists and get the count of matched values in python

I have two lists with some items in common and some not. I would like to compare the two lists and get the count of items that matched.
list1 = ['apple','orange','mango','cherry','banana','kiwi','tomato','avocado']
list2 = ['orange','avocado','kiwi','mango','grape','lemon','tomato']
Pls advice how to do this in python
Use Counters and dictionary comprehension.
list1 = ['apple','orange','mango','cherry','banana','kiwi','tomato','avocado']
list2 = ['orange','avocado','kiwi','mango','grape','lemon','tomato']
c1 = Counter(list1)
c2 = Counter(list2)
matching = {k: c1[k]+c2[k] for k in c1.keys() if k in c2}
print(matching)
print('{} items were in both lists'.format(len(macthing))
Output:
{'avocado': 2, 'orange': 2, 'tomato': 2, 'mango': 2, 'kiwi': 2}
5 items were in both lists
I think you can use set.intersection within a comprehension like this example:
list1 = ['apple','orange','mango','cherry','banana','kiwi','tomato','avocado']
list2 = ['orange','avocado','kiwi','mango','grape','lemon','tomato']
result = {elm: list1.count(elm) + list2.count(elm) for elm in set.intersection(set(list1), set(list2))}
Output:
{'kiwi': 2, 'avocado': 2, 'orange': 2, 'tomato': 2, 'mango': 2}

Resources