I have a dictionary
{1:’one’,2:’two’}
I want to reverse it using a function and became to the following
{‘1:’eno’,2:’owt’ }
How can I do it?
Similarly, if I have a list or tuple like [15,49], how can I convert it to [94,51]?
You can use a simple dict comprehension, using the fact that string[::-1] reverses a string:
>>> d = {1: "one", 2: "two"}
>>> {x: v[::-1] for x, v in d.items()}
{1: 'eno', 2: 'owt'}
You could also define a function:
def reverse_values(dct):
for key in dct:
dct[key] = dct[key][::-1]
Which will alter the values in the same dict.
>>> reverse_values(d)
>>> d
{1: 'eno', 2: 'owt'}
For converting list of type [15,49] to [94, 51], you can try the snippet below (this will work for lists of type [12, 34, 56, 78] to [87, 65, 43, 21] as well):
>>> l = [15,49]
>>> [int(str(x)[::-1]) for x in l[::-1]]
[94, 51]
For your question here, use the following:
Given that [::-1] reverses the string, we can convert each number to a string, reverse each item, convert back to an integer, then reverse the entire list:
>>> lst = [15, 49]
>>> [int(str(item)[::-1]) for item in lst][::-1]
[94, 51]
>>>
Related
Suppose
List1 = [ 23, 45, 6, 7, 34]
List2 = [46, 23, 1, 14, 68, 56]
Compare List1 and List2 and print the element of List1 which have a double value in List2
Output = [23,7,34]
Try this:
Output = [i for i in List1 if i*2 in List2]
You can convert list2 to a set for efficient lookups, and use a list comprehension with the said condition for the desired output:
set2 = set(List2)
[i for i in List1 if i * 2 in set2]
You already have the answer but just of the sake of simplicity. Basically you want to iterate through List1 and check if double value is in List2. If so add element to the output array.
List1 = [ 23, 45, 6, 7, 34]
List2 = [46, 23, 1, 7, 14, 68, 56]
output = []
for i in List1:
if i*2 in List2:
output.append(i)
print output
You already got the answers. However, just for fun, I came up with the following method. I did not benchmark all the approaches listed here. It can be fun to do that. This is an interesting question and can be investigated more. However, just for the sake of it I present the solution I did.
import numpy as np
l = np.array(List1) * 2
print(l)
## array([46, 90, 12, 14, 68])
print(set(l) & set(List2))
## {68, 46, 14}
l2 = set(l) & set(List2)
print([List1[list(np.nonzero(l == i))[0][0]] for i in l if i in l2])
## [23, 7, 34]
It uses the broadcasting of numpy along with the fast intersection operation of Python set. This maybe useful if the two lists are very big.
l=[1,4,5,6,3,2,4,0]
I want the to out come to be
newlist=[14,56,32,40]
I have tried
for i in l[::2]:
newlist.append(i)
what to do
You can use zip() function within a list comprehension:
>>> lst = [1,4,5,6,3,2,4,0]
>>> [i*10+j for i,j in zip(lst[0::2],lst[1::2])]
[14, 56, 32, 40]
As a more general approach for covering the list with odd number of items you can use itertools.izip_longest (in python 3.X itertools.zip_longest) :
by passing the 0 as fillvalue argument:
>>> lst=[1,4,5,6,3,2,4]
>>>
>>> from itertools import izip_longest
>>> [i*10+j for i,j in izip_longest(lst[0::2],lst[1::2], fillvalue=0)]
[14, 56, 32, 40]
An alternate solution, just for fun
lst = [1,4,5,6,3,2,4,0]
it = iter(lst)
for i in it:
num = int(str(i) + str(next(it)))
print num
lst = [1,4,5,6,3,2,4,0,1]
length = len(lst)
newList = [i*10+j for i,j in zip(lst[::2],lst[1::2])]
if length % 2 == 1:
newList.append(lst[-1]*10)
print newList
Output:
[14, 56, 32, 40, 10]
I have seen solutions for counting of values within a simple list, but what if you have a list of lists?
Example:
list = [[Frank, 23],[Mary, 55],[Craig, 17],[Nancy, 34],[Ben, 55],[Cindy, 47]]
How would I count the number of times the second value of each sublist is 55?
Given:
>>> li = [['Frank', 23],['Mary', 55],['Craig', 17],['Nancy', 34],['Ben', 55],['Cindy', 47]]
You can invert the matrix:
>>> zip(*li)
[('Frank', 'Mary', 'Craig', 'Nancy', 'Ben', 'Cindy'), (23, 55, 17, 34, 55, 47)]
And count the 55's in the nth element:
>>> zip(*li)[1].count(55)
2
OR, you can use itemgetter and get the nth item:
>>> from operator import itemgetter
>>> map(itemgetter(1), li)
[23, 55, 17, 34, 55, 47]
>>> map(itemgetter(1), li).count(55)
2
If you want ALL the counts, use a Counter:
>>> from collections import Counter
>>> Counter(zip(*li)[1])
Counter({55: 2, 17: 1, 34: 1, 47: 1, 23: 1})
Make a new generator out of it and pass it to sum():
>>> l = [['Frank', 23],['Mary', 55],['Craig', 17],['Nancy', 34],['Ben', 55],['Cindy', 47]]
>>> sum(item[1]==55 for item in l)
2
Also, don't name it list, or that masks the built-in function list().
End Goal to create the following Dictionary
DictFinal = {'peach': [7,33], 'berries': [33,47], 'grapes': [47,98], 'apple': [98,200]}
snippets of code
FinalEndofline = 200
List1 = ["apple","peach","grapes","berries"]
List2 = [98,7,47,33]
Step1 : To create a dictionary using key value.List1 is the key and List2 is value.
professions_dict = dict(zip(List1, List2))
print professions_dict
Output - {'apple': 98, 'peach': 7, 'grapes': 47, 'berries': 33}
Step 2 : Sort the dictionary based on value
sorted_x = sorted(professions_dict.items(), key=operator.itemgetter(1))
print sorted_x
Output - {'peach': 7, 'berries': 33, 'grapes': 47, 'apple': 98}
Step 3 : Now how do I achieve
DictFinal = {'peach': [7,33], 'berries': [33,47], 'grapes': [47,98], 'apple': [98,200]}
The Dictfinal is again a key value, but a value having the list with first value and second value and goes on and it appends the finalendofline variable to last value list
>>> List1 = ["apple","peach","grapes","berries"]
>>> List2 = [98,7,47,33]
>>> List1 = [x[1] for x in sorted(zip(List2, List1))]
>>> List2.sort()
>>> List2.append(200)
>>> DictFinal = dict((key, List2[i:i+2]) for i, key in enumerate(List1))
>>> DictFinal
{'berries': [33, 47], 'grapes': [47, 98], 'peach': [7, 33], 'apple': [98, 200]}
That's fairly straightforward. This is probably a bit more efficient, though -- only requires one sort(). If efficiency really matters, you could also use itertools to do the slice on the second zip (and, of course, with Python 2, you would want to use izip instead of zip).
>>> List1 = ["apple","peach","grapes","berries"]
>>> List2 = [98,7,47,33]
>>> zipped = sorted(zip(List2, List1)) + [(200,)]
>>> FinalDict = dict((x[1], [x[0], y[0]]) for x, y in zip(zipped, zipped[1:]))
Maybe try:
List2 = ["""Blah""",FinalEndofLine]
unsorted = dict(zip(List1,[[List2[i],List2[i+1]] for i in range(len(l2) - 1)]))
DictFinal = sorted(unsorted.items(), key = lambda x: x[1][0])
This seemed to work for me, if I understand your problem fully. List2 just needs that FinalEndofLine at the end.
I have a list of lists and inside the lists are strings of multiple numbers. For example,
[['34,53,53,21'], ['43,65,12,53'], ['54,23,31,34']]
and I want the result to look like:
[[34,53,53,21], [43,65,12,53], [54,23,31,34]]
with all integers inside. I've tried numerous code, but keep getting different error messages.
Also, what about if some of the interior numbers were a float? Such as:
[['34,53.09,53.56,21.98'], ['43,65.67,12.45,53.45'], ['54,23.34,31.23,34.76']]
>>> L = [['34,53,53,21'], ['43,65,12,53'], ['54,23,31,34']]
>>> [[int(y) for y in x[0].split(',')] for x in L]
[[34, 53, 53, 21], [43, 65, 12, 53], [54, 23, 31, 34]]
For floats:
>>> L = [['34,53.09,53.56,21.98'], ['43,65.67,12.45,53.45'], ['54,23.34,31.23,34.76']]
>>> [[float(y) for y in x[0].split(',')] for x in L]
[[34.0, 53.09, 53.56, 21.98], [43.0, 65.67, 12.45, 53.45], [54.0, 23.34, 31.23, 34.76]]
[[int(y) for y in x[0].split(',')] for x in lst]
On python 2.x, you could use:
[map(int,x[0].split(',')) for x in lst]
And in some ways, having inner list of the strings is inconvenient. You could use chain to remove them:
from itertools import chain
[[int(y) for y in x.split(',')] for x in chain.from_iterable(lst)]