Python: merge two ordered lists, replacing elements conditionally - python

Beginner's question.
I have two ordered lists with the same order,
list_1=['de', 'de', 'de', '3']
list_2=['6', '5', '3', 'not']
so the n-th element of list_1 corresponds to the n-th element of list_2.
I want to merge the two lists while perserving their order. Moreover, the list resulting from the merge should consist entirely out of numbers, i.e.
merged_list=['6', '5', '3', '3']
Preferably, I merge by position in the list conditionally on string or numeric values. I have the same issue with other ordered lists, but with those lists I want to replace numeric values with string values. I.a. to solve my troubles with all the ordered lists I have I'd like to do something like:
replace element_n of list_i with element_n of list_j if element_n of list_i equals 'z'
where z is either a numeric value or a string value, dependent on the nature of the list.

You can use zip to aggregates two list items:
>>> list_1 = ['de', 'de', 'de', '3']
>>> list_2 = ['6', '5', '3', 'not']
>>> zip(list_1, list_2)
<zip object at 0x1029e53c8>
>>> list(zip(list_1, list_2))
[('de', '6'), ('de', '5'), ('de', '3'), ('3', 'not')]
, and str.isdigit to check if the given string is a number:
>>> '123'.isdigit()
True
>>> 'de'.isdigit()
False
By combining with conditional expression and list comprehension, you will get what you want:
>>> [a if a.isdigit() else b for a, b in zip(list_1, list_2)]
['6', '5', '3', '3']

Related

How to sort a list that contains both numbers and letters?

I am trying to join and sort some list that contains numbers and letters
for example:
l1 = ['AF', '0.167']
l2 = ['AF', '1']
l3 = ['AC', '1']
l4 = ['AC', '6']
if I join l1 and l2 together, l3 and l4 together and reverse them (wish letters come first), I will get two different results.
['0.167', 'AF', '1']
['1', 'AF', '0.167']
--------------------
['6', '1', 'AC']
['AC', '1', '6']
why the second one can sort properly , but the first one only switch the positions of numbers.
if I expect to get :new1 =['AF', '0.167, 1'] , new2 = ['AC', '1, 6']
How can I change the code.
The code is here:
l1 = ['AF', '0.167']
l2 = ['AF', '1']
l3 = ['AC', '1']
l4 = ['AC', '6']
new1 = l1 + l2
new1 = list(set(new1))
new2 = l3 + l4
new2 = list(set(new2))
list(reversed(new1))
list(reversed(new2))
print( new1 )
print(list(reversed(new1)) )
print('--------------------')
print( new2 )
print(list(reversed(new2)) )
There are a couple of things that need to be clarified:
Sets are unordered, doing list(set(thing)) will give you a list with "random" order
reversed() does exactly what it sounds like, it enables you to iterate in reversed order, it doesn't do any sorting. If you want sorting, use sorted()
If I understand correctly, you want your strings to come first, followed by the sorted "numbers" (which are actually strings containing representation of numbers).
To do this, you'll need an appropriate sorting function. Something like the following should work:
>>> test1 = ['0.167', 'AF', '1']
>>> test2 = ['6', '1', 'AC']
>>> sort_key = lambda s: float('-inf') if s.isalpha() else float(s)
>>> sorted(test1, key=sort_key)
['AF', '0.167', '1']
>>> sorted(test2, key=sort_key)
['AC', '1', '6']
Depending on your data, having dict with strings as keys and a list of numbers as value might make more sense for storing it, and would be simpler to sort.

max method of a list consisting of strings

I am wondering why the result is '4' if I write the following code:
lists = ['1','2','3','4']
print(max(lists))
lists.append(5)
print(max(lists))
I suppose that the max method of lists converts from str to int first and then gives me the max of ints in the first couple of lines, but this seems untrue if I try the next lines. Can anyone explain this?
Your list contains strings and you are appending an integer.
lists = ['1', '2', '3', '4', 5]
TypeError: '>' not supported between instances of 'str' and 'int'
If you had only strings or only int's max will do the comparison as the '>' operator will work. You need to convert the list to all strings or all ints.
lists = [int(x) for x in lists] #by list comprehension
>>> max(lists) # lists= [1, 2, 3, 4, 5]
>>> 5
lists = [str(x) for x in lists]
>>> max(lists) # lists = ['1', '2', '3', '4', '5']
>>> '5'
If you have not yet seen list comprehensions it's doing this but much faster and in a single line of code.
new_list = []
for x in lists:
x = int(x) #convert each individual term to integer objects
new_list.append(x)
lists = new_list
Actually, it doesn't give you TypeError it will return '4' for both cases below:
list = ['1', '2', '3', '4']
list = ['1', '2', '3', '4', 5]
because when comparing objects in python, str always > int that's why you are getting '4' as the max value because it is the highest value among the strings
here is an example to prove what I'm saying:
>print '1' > 5
True
>print '1' > '5'
False
You can try this:
lists = ['1','2','3','4']
print(max(list(map(int, lists))))
lists.append(5)
print(max(list(map(int, lists))))

How to use a dictionary to print its partner value

Not sure if the title is specific enough.
words = ['sense', 'The', 'makes', 'sentence', 'perfect', 'sense', 'now']
numbers = ['1', '2', '3', '4', '5', '6']
dictionary = dict(zip(numbers, words))
print(dictionary)
correctorder = ['2', '4', '7', '3', '5', '6']
I'm simply trying to figure out how exactly I can print specific values from the dictionary using the correctorder array so that the sentence makes sense.
You can just iterate over correctorder and get the corresponding dict value, then join the result together.
' '.join(dictionary[ele] for ele in correctorder)
This is assuming that you fix numbers to include '7' at the end.
>>> ' '.join(dictionary[ele] for ele in correctorder)
'The sentence now makes perfect sense'
What you want is this.
for i in correctorder:
print dictionary[i]," ",
Short and simple. As Mitch said, fix the 7 though.
You could use operator.itemgetter to avoid an explicit loop:
>>> from operator import itemgetter
>>> print(itemgetter(*correctorder)(dictionary))
To concatenate this simply use str.join:
>>> ' '.join(itemgetter(*correctorder)(dictionary))

how to match items between 2 different lists

I have 2 different lists:
['2', '1']
['equals', 'x']
I want to match the items so 2 = "equals" and 1 = "x" in order to recreate the original sentence "x equals x", also i have a third list which is:
['1', '2', '1']
I need the third list to recreate the original sentence since it has all the positions, to do this I thought of making the numbers equal to the words such as 1 = "x" and printing the list of numbers in order to have the full sentence. The problem is i do not know how to make the numbers equal to the words. Thanks for the help in advance
A dictionary might be what you need here which maps keys to values. You can create a dictionary from the first two lists by zipping them. And with this dictionary, it should be fairly straight forward to map any list of numbers to words:
mapping = dict(zip(['2', '1'], ['equals', 'x']))
mapping
# {'1': 'x', '2': 'equals'}
[mapping.get(num) for num in ['1', '2', '1']]
# ['x', 'equals', 'x']
To make the list a sentence, use join method:
" ".join(mapping.get(num) for num in ['1', '2', '1'])
# 'x equals x'

How to break a python list tuple into tuple with two elements?

I have a list and want to split each elements into a tuple of two elements.
The list looks like:
list_doctors = ['dr.naman_5','dr.akanksha_7','dr.sumant_3']
How do I create a list of the form:
modified_list = [('dr.naman','5'),('dr.akanksha','7'),('dr.sumant','3')]
Try the following.
>>> list_doctors = ['dr.naman_5','dr.akanksha_7','dr.sumant_3']
>>> [tuple(s.split('_')) for s in list_doctors]
[('dr.naman', '5'), ('dr.akanksha', '7'), ('dr.sumant', '3')]
Use split().
>>> list_doctors = ['dr.naman_5','dr.akanksha_7','dr.sumant_3']
>>> modified_list = [item.split('_') for item in list_doctors]
>>> modified_list
[['dr.naman', '5'], ['dr.akanksha', '7'], ['dr.sumant', '3']]

Categories

Resources