[英]Enumerate in Python variable positions
i'd like to know: what's the difference between these two:我想知道:这两者有什么区别:
return "-".join([c.upper() + c.lower() * i for i,c in enumerate(txt)])
return "-".join([c.upper() + c.lower() * i for c,i in enumerate(txt)])
I just changed the 'i' with the 'c' and the whole code doesn't work.我只是用 'c' 更改了 'i',整个代码不起作用。 Is there a simple explanation?
有没有简单的解释?
Yes.是的。
enumerate()
yields pairs of (index, item)
from a given iterable. enumerate()
从给定的可迭代对象中生成(index, item)
对。
For a string "hello"
, it would return (formatted as a list)对于字符串
"hello"
,它将返回(格式化为列表)
[
(0, 'h'),
(1, 'e'),
(2, 'l'),
(3, 'l'),
(4, 'o'),
]
For the sake of simplicity, let's look at the first item only, (0, 'h')
.为简单起见,让我们只看第一项,
(0, 'h')
。
If you use i, c
to unpack this, i
's value will be 0
, and c
's value will be 'h'
, and c.lower()
etc. makes sense, as does multiplication with the number i
.如果你使用
i, c
来解包, i
的值将是0
, c
的值将是'h'
, c.lower()
等是有道理的,乘以数字i
。
If you use c, i
to unpack this, c
's value will be 0
, and i
's value will be 'h'
, and c.lower()
no longer exists since c
is a number and i
is a string.如果你使用
c, i
来解包, c
的值为0
, i
的值为'h'
, c.lower()
不再存在,因为c
是一个数字, i
是一个字符串。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.