简体   繁体   English

在 Python 变量位置枚举

[英]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的值将是0c的值将是'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的值为0i的值为'h'c.lower()不再存在,因为c是一个数字, i是一个字符串。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 python枚举中未使用的变量 - Unused variable in python enumerate 如何在不使用枚举或正则表达式的情况下查找字符串中字符的所有位置? - How to find all positions of a character in a string without using enumerate or regex in Python? 在python中枚举 - enumerate in python Python 将变量 dict 位置传递给 function - Python pass variable dict positions to function 如何在 python 中重新安装变量时使用枚举进行列表理解 - How to make a list comprehesion with enumerate while reseating a variable in python 如何使用枚举将文件的特定行读取到python中的变量? - How to read a specific line of a file to a variable in python using enumerate? 在python中,[pos for pos,如果word == word_positions,则enumerate(sentence,start = 1)中的单词]在我的代码中实际上是做什么的? - In python what does [pos for pos, word in enumerate(sentence, start=1) if word == word_positions] actually do in my code? 查找仅在 Python 中特定位置处可变的字符串的所有排列 - Find all permutations of a string that is variable only at specific positions in Python (Python) Networkx - 如何使用 pos 变量为节点设置自己的位置 - (Python) Networkx - How to set own positions for nodes with pos variable Python:浮点到小数点后位置数可变的字符串 - Python: Float to string with variable number of positions after the decimal point
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM