![](/img/trans.png)
[英]Python - Create multiple lists from elementwise concatenation of two lists
[英]Python - String concatenation from multiple lists?
我需要生成一個文件,其中每一行是句子(模板)和四個變量的串聯。 這四個變量(分別是它們的值)先前已收集在單獨的列表中。 到目前為止,我嘗試過:
num = [1,2,3]
fruit = [grape ,banana,pea]
fruits = [grapes, bananas, peas]
with open('result', 'w') as r:
for n,f,g in num,fruit,fruits:
r.writelines("This is string number %d. This is a %s. And I like to eat %s" % (num[n],fruit[f],fruits[g]))
......這種做法提出了:
TypeError: list indices must be integers, not tuple
。
我也沒有與不同的列表一起“mungling”這個,即首先將第一個和第二個變量+字符串與中間列表連接起來,以減少“復雜性”。
有人能給我一個暗示我失敗的地方嗎?
解決問題的更慣用的方法是:
template = "This is string number {}. This is a {}. And I like to eat {}\n"
with open('result', 'w') as r:
for n, f, fs in zip(num, fruit, fruits):
r.write(template.format(n, f, fs))
請注意以下事項:
in num,fruit,fruits
中創建了一個包含三個列表的元組; 您必須使用zip()
將輸入列表打包在一起並同時遍歷它們 n,f,g
迭代變量引用列表中的實際元素 ,而不是索引。 這就是為什么這個片段: num[n],fruit[f],fruits[g]
引發錯誤 %
語法,應該避免使用format()
writelines()
用於寫一個行列表,用於在寫入單行時使用write()
傳遞一個\\n
-terminated字符串 對於python中的語句具有以下語法。
for <value> in <iterable>:
body
List is a <iterable> data type.
現在,這意味着你可以遍歷它。 我建議你閱讀文檔,了解有關iterables以及如何在類定義中實現它們的更多信息。
但列表,列表,列表不是。 您需要將這些列表連接到一個列表中。
zip(l1,l2,l3)會為你做模式匹配。 它會創建一個列表,其元素與元組中的索引匹配。
你可以在價值上取消它
在你的情況下
for (n,f,g) in zip(num,fruit,fruits):
會做。
num,fruit,fruits
給出一個元組,它for n,f,g in num,fruit,fruits:
等於:
atuple=num,fruit,fruits
for n,f,g in atuple:
...
所以for循環解包atuple[0]
(即num
),將值num[0], num[1], num[2]
分配給n,f,g
,然后是fruit[0], fruit[1], fruit[2]
......這就是你得到錯誤的原因。
for n,f,g in num,fruit,fruits:
更改for n,f,g in num,fruit,fruits:
to:
for tup in zip(num,fruit,fruits):
r.writelines("This is string number %d.
This is a %s. And I like to eat %s" % tup)
請參閱zip文檔
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.