Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/loops/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 检测循环中的最后一次迭代_Python_Loops_Iteration - Fatal编程技术网

Python 检测循环中的最后一次迭代

Python 检测循环中的最后一次迭代,python,loops,iteration,Python,Loops,Iteration,我有一个单词,我想从一个单词中拆分每个字符。我使用FOR IN循环分割字符。在分割期间,我想检测第一个和最后一个字符。我使用一个变量count,count被初始化为0。如果count=1,则它是第一个字符。但类似地,如何在python中检测FOR-in循环中的最后一个字符 count=0; for w in word: count++ if count==1: #first character 为什么不直接使用枚举?正是为

我有一个单词,我想从一个单词中拆分每个字符。我使用FOR IN循环分割字符。在分割期间,我想检测第一个和最后一个字符。我使用一个变量count,count被初始化为0。如果count=1,则它是第一个字符。但类似地,如何在python中检测FOR-in循环中的最后一个字符

    count=0;
    for w in word:
        count++
        if count==1:
            #first character

为什么不直接使用
枚举
?正是为了这个目的

for i, w in enumerate(word):
    if i in {0, len(word)-1}:
        ... # do something

您现在可以去掉
count
变量。

为什么不直接使用
enumerate
?正是为了这个目的

for i, w in enumerate(word):
    if i in {0, len(word)-1}:
        ... # do something

现在可以去掉count变量。

如果只想获取第一个和最后一个字符,可以使用第一个和最后一个索引

s = 'word'
s[0] >>> 'w'
s[-1] >>> 'd'

如果只想获取第一个和最后一个字符,可以使用第一个和最后一个索引

s = 'word'
s[0] >>> 'w'
s[-1] >>> 'd'

这不是个好主意。如果最后一个字符在别处,你会早点休息。这不是个好主意。如果最后一个字符存在于其他地方,您可以提前中断。如果i==len(word)-1,为什么不使用
呢?Florent他们想同时检测第一个和最后一个字符。如果i==len(word)-1
,为什么不使用
呢?Florent他们想同时检测第一个和最后一个字符。