我想在Python 3.3中通过索引将列表加入到字符串中.我可以为彼此跟随的项目做这件事,但我想通过索引访问它.
这工作:
list = ['A', 'B', 'C', 'D']
partList = "".join(list[1:3])
-> BC
Run Code Online (Sandbox Code Playgroud)
但是我怎样才能做到这一点(它不起作用):
list = ['A', 'B', 'C', 'D']
partList = "".join(list[0,3])
-> AD
Run Code Online (Sandbox Code Playgroud)
您不能使用切片表示法将列表切片为任意块.对于一般情况,你可能最好的选择是使用索引列表来构建列表理解.
mylist = ['A', 'B', 'C', 'D'] # the full list
indices = [0, 3] # the indices of myList that you want to extract
# Now build and join a new list comprehension using only those indices.
partList = "".join([e for i, e in enumerate(mylist) if i in indices])
print(partList) # >>> AD
Run Code Online (Sandbox Code Playgroud)
正如DSM的评论所指出的那样,如果你关注效率,你知道你的指数列表将是"友好的"(也就是说,它不会有任何指数对于你正在削减的列表而言太大) ,您可以使用更简单的表达式,而无需enumerate:
partList = "".join([mylist[i] for i in indices])
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
8992 次 |
| 最近记录: |