[英]Unpacking of list in function but not needed when its done with MAP()?
def ups(*name):
for n in name:
a=n.upper()
return a
lis=["lan","ona"]
m=list(map(ups,lis))
print(m)
在 map 中,我沒有對列表進行解包,但在 function 調用沒有 Map() 的情況下也是如此,(例如)像ups(*lis)
是必須的,為什么?
學習,謝謝
除了ksourav的回答,
map(function, iterable, ...)
“返回 [s] 一個迭代器,它將 function 應用於 iterable 的每個項目,從而產生結果”。 正如 ksorav 在他的回答中指出的那樣,您傳遞的項目是字符串,因此本身就是可迭代的 - 所以 function 只返回最后一個大寫字母,比如s = 'lan'
for char in s:
print(char.upper())
# L
# A
# N
tuple
而不是字符串的單個元素。 這就是為什么在這里,您的 function 以大寫字母返回整個單詞,例如t = ('lan',)
for element in t:
print(element.upper())
# LAN
m = list(map(lambda x: x.upper(), lis))
# or even better
m = [s.upper() for s in lis]
star( )args means variable number of arguments.so basically your fuction can take variable number of arguments.On the other hand map function takes a function and a list as argument and the function is called on each element of the list that was passed as argument.so 如果您在定義的 function 中不使用“ ”,那么它將在 lis 中使用一個刺痛(當您傳入 map 函數時)並迭代它並返回唯一的最后一個字母每個字符串都是大寫的。因為for循環將遍歷傳遞的元素,但只返回最后一個元素,因為你只返回一個。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.