![](/img/trans.png)
[英]How to iterate through a list of string tuples of varying lengths in Python?
[英]How to iterate through a list of strings with different lengths?
假設我有
lists = ["ABC","AC","CCCC","BC"]
我想要一個新列表,其中新列表中的項目將基於列表按位置分組,這意味着lists
中的每個字符串都將位置0(“ ABC”位置0為“ A”)並從中制成字符串。
position = ["AACB","BCCC","CC","C"]
我嘗試:
for i in range(0,4): want = [lists[i] for stuff in lists]
我得到
IndexError: string index out of range
這是有道理的,因為所有字符串的大小都不同。 有人可以幫忙嗎?
我認為您可能想要這樣:
import itertools
lists = ["ABC","AC","CCCC","BC"]
position = map(''.join,itertools.izip_longest(*lists, fillvalue=''))
你會得到:
['AACB', 'BCCC', 'CC', 'C']
編輯:現在有了新的例子...
您可以使用以下列表理解:
>>> lists = ["ABC","AC","CCCC","BC"]
>>> [''.join([s[i:i+1] for s in lists]) for i, el in enumerate(lists)]
['AACB', 'BCCC', 'CC', 'C']
使用切片符號可以防止不存在的元素出現索引錯誤。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.