[英]concatenating python strings in a loop
我正在使用枚舉和string.join()方法在Python中形成幫助字符串:
我有以下代碼段:
from enum import Enum
class Estimators(Enum):
rsac = 1
msac = 2
現在,我創建一個幫助字符串,如下所示:
est_help = 'Valid options are: [' + (str(i.name) + ', ' for i in Estimators) + ']'
這將引發TypeError異常,如下所示:
TypeError: cannot concatenate 'str' and 'generator' objects
我想知道我在做什么錯。 i.name
是字符串類型。
該錯誤消息告訴您您在做什么錯-嘗試連接字符串和生成器。 您要做的是使用基於生成器的列表理解來創建列表,然后使用該列表
est_help = 'Valid options are: [{}]'.format( ', '.join( i.name for i in Estimators))
讓我們將其分解為各個步驟:
[rsac,msac]
: est_list = [str(i.name) for i in Estimators]
'rsac, msac'
分隔的字符串: est_str = ', '.join( est_list )
est_help = 'Valid options are: [{}]'.format( est_str )
,並得到結果字符串Valid options are: [rsac, msac]'
編輯:修改后的代碼結合了注釋中的建議
est_help = 'Valid options are: [{}]'.format( ', '.join( i.name for i in Estimators ) )
您可以加入Estimators的成員:
'Valid options are: [%s]' % ', '.join(Estimators.__members__)
解
est_help = 'Valid options are: [' + ",".join(str(i) for i in Estimators) + ']'
由於沒有提到的帖子對我有用(我總是得到'type'對象是不可迭代的,@lvc知道了這一點,所以我從PyPI獲得了枚舉,但沒有內置迭代器功能),這是我的解決方案問題
from enum import Enum
class Estimators(Enum):
rsac = 1
msac = 2
e = Estimators
attributes = [attr for attr in vars(e) if not attr.startswith('__')]
est_help = 'Valid options are: ' + str(attributes).replace('\'','')
print est_help
我使用vars獲取類的成員,因為它們以字典格式存儲,然后過濾掉所有以__
開頭的成員,然后由於列表中的元素顯示為字符串'
我用空字符串替換了它們。
如果將我的解決方案與@SigveKolbeinson的答案結合在一起,則可以減少一些代碼
est_help = 'Valid options are: [{}]'.format( ', '.join( [str(i) for i in vars(Estimators) if not i.startswith('__')]))
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.