簡體   English   中英

修改Python列表的每個元素,並將結果組合成字符串

[英]Modify each element of a Python list and combine results into a string

假設有一個“ dog”類型的對象列表,每個狗都有一個“ name”參數。 例如:

dogs = [dog1, dog2, dog3]  

是由三只名叫Rocky,Spot和Daisy的狗組成的列表。

我正在嘗試訪問每只狗的“名稱”,並生成一個字符串,例如“ Rocky,Spot,Daisy”。 我知道我需要使用列表推導,但是事實證明,這些細節比我想象的要難。

我嘗試使用

result = (dog.name+", " for dog in dogs)  

但是結果成為生成器而不是字符串。

我也試過

result = ",".join(layers.name) 

但是我沒有找到訪問每只狗的“名稱”字段的方法。

我知道如何使用蠻力解決問題,但是我真的想實現一個優雅的“ python”解決方案。 任何幫助將不勝感激!

您必須將生成器與join結合使用:

result = ', '.join(dog.name for dog in dogs)  

您可以將生成器插入join。

>>> ", ".join(dog.name for dog in dogs)
'Rocky, Spot, Daisy'

這個:

result = (dog.name+", " for dog in dogs)

是生成器理解/表達式,而不是列表理解。 您可以這樣使用:

>>> dogs = ['Rocky', 'Spot', 'Daisy']
>>> result = (dog for dog in dogs)
>>> for dog in result:
...     print(dog)
...
Rocky
Spot
Daisy

或針對您的特定情況:

>>> result = (dog for dog in dogs)
>>> ', '.join(result)
'Rocky, Spot, Daisy'

如果將列表理解與", ".join結合使用", ".join則會得到:

result = ", ".join( [dog.name for dog in dogs] )

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM