[英]List of strings to tuples
晚上好,
我正在嘗試從字符串列表中創建一個元組。 然而,它的行為並不像預期的那樣。 任何人都可以啟發我嗎?
l = ['NP', 'shot']
tups = map(lambda x: tuple(x), l[-1])
# Desired result
print(tups) #('shot')
# Result
print(tups) # [('s',), ('h',), ('o',), ('t',)]
# or
print(tups) # <map object at 0x000000001691FD00>
您可以簡單地使用括號:
l = ['NP', 'shot']
tups = (l[-1],)
print(tups) # ('shot')
您想為此使用內置的 tuple() function
l = ['NP', 'shot']
tups = tuple(l)
print(tups)
如果,就像一個思想實驗,你希望map
工作,你會這樣做:
>>> l = ['NP', 'shot']
>>> next(map(lambda x: (x,), [l[-1]]))
('shot',)
這樣做要好得多:
>>> tuple([l[-1]])
('shot',)
或者使用文字元組構造函數形式:
>>> (l[-1],)
('shot',)
可以縮短為:
>>> l[-1],
('shot',)
使用tuple([l[-1]])
你需要一個可迭代的容器——在這種情況下是一個列表——這樣你就不會得到('s', 'h', 'o', 't')
您不需要使用(l[-1],)
因為 arguments 不會迭代文字; 他們只被評估:
>>> (1+2,) #1+2 will be evaluated
(3,)
>>> ("1+2",) # the string "1+2" is not iterated...
('1+2',)
>>> tuple(1+2) # self explanatory error...
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'int' object is not iterable
>>> tuple("1+2") # string is iterated char by char
('1', '+', '2')
嘗試這個:
tuple(map(str, l[-1].split(",")))
它的字面意思是
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.