gpt4 book ai didi

python - 理解 python 中的 Zip 和列表理解

转载 作者:太空宇宙 更新时间:2023-11-04 11:14:10 25 4
gpt4 key购买 nike

我有一个函数“to_underscore”,它接受 CamelCase 字符串并将其转换为 snake_case

def to_underscore(string):
index_counter = []

if isinstance(string, int):
return str(string)

for i in range(len(string)):
if string[i].isupper():
index_counter.append(i)

new_string = [string[i:j] for i,j in zip (index_counter,index_counter[1:] + [None])]
string = '_'.join(new_string)

return ''.join(c.lower() for c in string)

我不太明白下面一行是如何执行的:

string = "ThisIsCamelCase"
index_counter = [0,4,6,11]

// this line - >
for i,j in zip (index_counter,index_counter[1:] + [None]):
print(i,j)

// output -> (0,4),(4,6),(6,11),(11,None)

index_counter[1:] +[None] 是什么意思?为什么这是输出?

我理解 zip 以及我们正在尝试做什么,但输出不清楚。

如果您可以逐步执行,这将是最佳选择。

最佳答案

index_counter = [0, 4, 6, 11]

现在,index_counter[1:] 是:

[4, 6, 11]

index_counter[1:] + [None] 是:

[4, 6, 11, None]

zip 使用 index_counter,然后迭代这些对:

0   4   6   11
4 6 11 None

None 需要添加,否则 zip 会在 (6, 11) 对处停止。相反,您也可以使用 itertools.zip_longest .

关于python - 理解 python 中的 Zip 和列表理解,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57409687/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com