您好我有一個這樣的名單:[1,2,3,4,5,6]
百分比符號添加到列表中的所有元素
我想補充"%"
到列表中的所有這些元素的[1%,2%,3%,4%,5%,6%]
結果。
我知道我可以用+"%"
做到這一點,但我怎樣才能做到這一點.format
或另一件事?
您好我有一個這樣的名單:[1,2,3,4,5,6]
百分比符號添加到列表中的所有元素
我想補充"%"
到列表中的所有這些元素的[1%,2%,3%,4%,5%,6%]
結果。
我知道我可以用+"%"
做到這一點,但我怎樣才能做到這一點.format
或另一件事?
當然,你可以用format
做到這一點,你當然結果需要字符串:
l = [1,2,3,4,5,6]
r = list(map("{}%".format, l))
現在,r
是:
['1%', '2%', '3%', '4%', '5%', '6%']
或者你可以用列表的補償做在對方的回答,或在地方,通過循環:
for ind, i in enumerate(l):
l[ind] = "{}%".format(i)
既然你問:or another thing?
我給你another thing
。
有時候,你會想要的東西,這似乎有點壞,像這樣:
# add method to built-in int class to render ints as percents
as_percent = lambda x: str(x) + '%'
# and then monkey patch it
int.as_percent = as_percent
但是你最終這個Exception
:
TypeError: can't set attributes of built-in/extension type 'int'
但是,有一種方法..
之前你會嘗試以下a 小免責聲明:
我從來沒有在任何實際的代碼中使用過這個,但我覺得這非常有趣,並且通常很好地知道它存在。在Ruby中有一點代碼,我喜歡猴子修補內置的想法。但它不是Python中的默認行爲。所以,請注意。但至少,試試吧!
首先,你需要這個模塊forbiddenfruit
(看到,名是相當不言自明!)。只需pip
吧。
然後它很容易。我們將像以前一樣使用lambda
函數as_percent
。
>>> from forbiddenfruit import curse
>>> # again, do you see the name of the function?!
>>> curse(int, 'as_percent', as_percent)
>>> print((1).as_percent())
1%
>>> [x.as_percent() for x in range(10)]
>>> ['0%', '1%', '2%', '3%', '4%', '5%', '6%', '7%', '8%', '9%']
我碰到過它here。
此鏈接可能會幫助你https://docs.python.org/3.1/library/string.html – JezEmery