[英]Python from tuples to strings
python編程的新手,在弄清楚這一點時遇到了一些困難。 我正在嘗試將元組轉換為字符串,例如('h','e',4)轉換為'he4'。 我已經使用.join函數提交了一個版本,並且我需要提出另一個版本。 我得到以下內容:
def filter(pred, seq): # keeps elements that satisfy predicate
if seq == ():
return ()
elif pred(seq[0]):
return (seq[0],) + filter(pred, seq[1:])
else:
return filter(pred, seq[1:])
def accumulate(fn, initial, seq):
if seq == ():
return initial
else:
return fn(seq[0], accumulate(fn, initial, seq[1:]))
提示如何使用以下內容將元組轉換為字符串?
給定的filter
對此沒有用,但是給定的accumulate
可以輕松使用:
>>> t = ('h','e',4)
>>> accumulate(lambda x, s: str(x) + s, '', t)
'he4'
只需遍歷元組即可。
#tup stores your tuple
string = ''
for s in tuple :
string+=s
在這里,您將遍歷元組並將其每個元素添加到新字符串中。
1)使用reduce
功能:
>>> t = ('h','e',4)
>>> reduce(lambda x,y: str(x)+str(y), t, '')
'he4'
2)使用愚蠢的遞歸:
>>> def str_by_recursion(t,s=''):
if not t: return ''
return str(t[0]) + str_by_recursion(t[1:])
>>> str_by_recursion(t)
'he4'
您可以使用map並加入。
tup = ('h','e',4)
map_str = map(str, tup)
print(''.join(map_str))
Map有兩個參數。 第一個參數是必須用於列表中每個元素的函數。 第二個論點是可迭代的。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.