[英]How to convert list into string without loop and join() in Python
我有一個排序列表的任務,如下所示:
Input: "Sorting1234"
Output: "ginortS1324"
不使用join()方法中,或同時在代碼的任何地方。 經過大量嘗試以所需方式排序后,我成功了,但我無法將其打印為字符串
My Output is: ['g', 'i', 'n', 'o', 'r', 't', 'S', '1', '3', '2', '4']
這是我用sorted()排序的算法:
st=input()
def iseven(x):
if x.isdigit():
return int(x)+9 if int(x)%2==0 else int(x)
res=sorted(st, key=lambda x: (x.isdigit(), x.isupper(), iseven(x), ord(x) ))
print(res)
請幫幫我
但我無法將其打印為字符串
只需在調用print()
時使用*
運算符將參數解包出列表,並使用""
作為分隔符 :
>>> L = ['g', 'i', 'n', 'o', 'r', 't', 'S', '1', '3', '2', '4']
>>> print(*L, sep="")
ginortS1324
你可以使用reduce ,它不在禁止列表中。 在代碼末尾附加此行:
new_res=reduce( lambda x,y: x+y, res, "")
print(new_res)
不使用join,for或while:
print(reduce(lambda x,y:x+y, res, ''))
隱式使用循環,但回答你的問題!
說
>>> L = ['g', 'i', 'n', 'o', 'r', 't', 'S', '1', '3', '2', '4']
要將char列表轉換為不帶join
和顯式循環的字符串,可以使用array
模塊:
>>> from array import array
>>> array('c', L).tostring()
'ginortS1324'
或struct
模塊:
>>> from struct import pack
>>> pack('s' * len(L), *L)
'ginortS1324'
為避免import
,您可以使用字符串形式:
>>> ('{}'*len(L)).format(*L)
'ginortS1324'
要避免隱式循環,可以使用遞歸:
>>> def recjoin(array):
... return array[0] if len(array) == 1 else array[0] + recjoin(array[1:])
...
>>> recursive_join(L)
'ginortS1324'
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.