Is there an easy way, apart from looping, to convert this kind of representation to a list of integers?
s = ['0','1','2:5','0x4']
to
list_i=[0,1,2,3,4,5,0,0,0,0]
You can use a list comprehension with the ternary operator like this:
list_i = [i for t in s for i in ((lambda r: range(int(r[0]), int(r[1]) + 1))(t.split(':')) if ':' in t else (lambda r: [int(r[0])] * int(r[1]))(t.split('x')) if 'x' in t else (int(t),))]
or you can use a for
loop instead:
list_i = []
for token in s:
if ':' in token:
start, end = token.split(':')
list_i.extend(list(range(int(start), int(end) + 1)))
elif 'x' in token:
number, repeat = token.split('x')
list_i.extend([int(number)] * int(repeat))
else:
list_i.append(int(token))
No, there isn't. You need to handle the special strings seperately. You need to loop through the list, check if the given element is a simple integer, if so, convert it as it is. If the element being considered is special ( 0x4
or 2:5
in your case), you need code to handle it. Try this:
oldList = ['0','1','2:5','0x4']
def isInt(val):
try:
int(val)
return True
except ValueError:
return False
def convertRange(val):
l = val.split(':')
return [x for x in range(int(l[0]), int(l[1])+1)]
def convertRepetition(val):
l = val.split('x')
return [int(l[0]) for i in range(0, int(l[1]))]
newList = []
for elem in oldList:
if ':' in elem:
newList.extend(convertRange(elem))
elif 'x' in elem:
newList.extend(convertRepetition(elem))
elif isInt(elem):
newList.append(int(elem))
print(newList)
the convertRange()
and convertRepitition()
functions take care of the two special cases your question mentions.
If you have the freedom to redefine how the s-list is set, you can use python syntax like this
s = ['[0]','[1]','range(2,6)','[0]*4']
list_i = []
[exec('list_i+='+i) for i in s]
print(list_i)
# which outputs
[0, 1, 2, 3, 4, 5, 0, 0, 0, 0]
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.