use*_*969 2 python string list
我想将一个数字列表返回到字符串列表:我有一个列表
copy=[[1,'a'],[55,'b'],[100,'c], [11,d],[66,f]]
Run Code Online (Sandbox Code Playgroud)
如果我有一个列表code=[1,100,100,11,1,66,1]
,结果列表必须类似于以下列表:
['a','c','c','d','a','f','a']然后将其返回到序列seq=['accdafa']
这意味着,我将列表代码中的每个元素与列表副本的元素进行比较.例如,我1从代码中获取元素,并将其与副本列表的元素进行比较
code[0]=1
if code[0]==copy[0][0]:
seq.append(copy[0][1])
else:
go to the next element of the list 'copy'
Run Code Online (Sandbox Code Playgroud)
我试试代码:
for j in range(len(code)):
if code[j]==copy[0][0]:
seq.append(copy[0][1])
Run Code Online (Sandbox Code Playgroud)
我收到以下错误:
IndexError: list index out of range
Run Code Online (Sandbox Code Playgroud)
对于列表的其余元素,同样的事情 code
完美用于词典!
copy = [[1, 'a'], [55, 'b'], [100, 'c'], [11, 'd'], [66, 'f']]
copy_as_dict = dict(copy)
code = [1, 100, 100, 11, 1, 66, 1]
seq = ''.join(copy_as_dict[i] for i in code)
Run Code Online (Sandbox Code Playgroud)
每个列表项的第一个元素成为键,第二个元素成为值
迭代code,你抢值从字典每个键的code.通过空字符串连接它们将它们一起压缩成一个输出,'accdafa'
| 归档时间: |
|
| 查看次数: |
61 次 |
| 最近记录: |