For example, if my string is
lst= [44,44 , 44]
and my prefix lengths are
lens = [2, 2, 2]
for k,v in zip(key,value):
#dic[k] = v
dic[k].append(v)
I made this with defaultdict
od = collections.OrderedDict(sorted(dic.items(),reverse=True))
od-> OrderedDict([('44', [2,2,2])])
I want to iterate through the [2,2,2]
and make a string equivalent to
'44'[:2] + '44'[:2] + '44'[:2]
and end up with a single string like '444444'
.
For your original example (which seems a bit over-complicated):
import collections
x = collections.OrderedDict([('4444', [1, 1, 1, 1, 2])])
print(''.join([k[:v] for k, vs in x.items() for v in vs]))
Explanation:
''.join(<some list here>)
takes a list and joins its elements into a string separated by the given string. [k[:v] for k, vs in x.items() for v in vs]
is a list comprehension, taking every key k
and values vs
(which is a list in your case) from the items of a dictionary, and then taking every value v
from that list and adding k[:v]
for each combination to the list in order. In general, if you have a list and a string and you'd like to create a concatenation of prefixes of that string based on the lengths in the list:
s = '12345'
ls = [1, 1, 2, 1, 3]
result = ''.join([s[:l] for l in ls])
Not sure what good it would be though...
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.