Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/python-3.x/17.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 相邻列表:尝试使用while循环改进此脚本_Python_Python 3.x - Fatal编程技术网

Python 相邻列表:尝试使用while循环改进此脚本

Python 相邻列表:尝试使用while循环改进此脚本,python,python-3.x,Python,Python 3.x,所以我试图改进这个脚本,如果相邻项相等,它将返回bool from typing import List, Dict, TextIO, Tuple def adjacent_match(L: List[str]) -> bool: """Return True iff two adjacent items in L are equal. >>> adjacent_match(['A', 'B', 'B']) True >>> adjacent_matc

所以我试图改进这个脚本,如果相邻项相等,它将返回bool

from typing import List, Dict, TextIO, Tuple
def adjacent_match(L: List[str]) -> bool:
"""Return True iff two adjacent items in L are equal.

>>> adjacent_match(['A', 'B', 'B'])
True
>>> adjacent_match(['A', 'B', 'A'])
False
"""

result = False

for index in range(len(L)):
    if len(L) == 0:
        return result
    elif index == 0:
        result = L[index] == L[index + 1]
    elif 0 < index < (len(L) - 1):
        result = (L[index] == L[index + 1] or L[index] == L[index - 1])
    elif index == (len(L) - 1):
        result = L[index] == L[index - 1]
    if result == True:
        return result

return result
从输入导入列表、Dict、TextIO、Tuple
def相邻_匹配(L:列表[str])->bool:
“”“如果L中的两个相邻项相等,则返回True。”。
>>>相邻_匹配(['A','B','B']))
符合事实的
>>>相邻_匹配(['A','B','A']))
错误的
"""
结果=错误
对于范围(len(L))中的索引:
如果len(L)==0:
返回结果
elif索引==0:
结果=L[索引]==L[索引+1]
elif 0<指数<(len(L)-1):
结果=(L[索引]==L[索引+1]或L[索引]==L[索引-1])
elif指数==(长度(L)-1):
结果=L[索引]==L[索引-1]
如果结果==真:
返回结果
返回结果
所以我觉得这个脚本可以使用
while
循环来改进,但对我来说不起作用,我的目标是在不使用模块的情况下缩短它,有什么建议吗?

您可以使用(内置的,不需要导入)来检查相邻条件:

def adjacent_match(L):
    for x, y in zip(L, L[1:]):
        if x == y:
            return True
    return False
样本运行

>>> adjacent_match(['A', 'B', 'B'])
True
>>> adjacent_match(['A', 'B', 'A'])
False
使用
enumerate()
遍历列表中的项目,并跟踪项目在列表中的位置

对于第二个和后续位置的每个项目,将其与前一个项目进行比较

def adjacent_match(L):
    for position, item in enumerate(L):
        if position == 0:
            continue
        if item == L[position-1]:
            return True

    return False

只需运行输入数组中的每个元素(使用索引),但最后一个元素可以避免索引错误,并将其与下一个元素进行比较:

def相邻_匹配(arr):
对于范围内的i(len(arr)-1):
如果arr[i]==arr[i+1]:
返回真值
返回错误

听起来像是“给你-这段代码做它做的事-用一段时间重写它”-家庭作业。@PatrickArtner这是家庭作业,代码工作了,但我这么问是因为代码的长度让我感到不舒服,我认为
while
循环可能工作得更好当使用一个内置循环时,使用两个:
返回any(x==y代表x,y在zip中(L,L[1:]))
请您指出在我的脚本中哪里可以找到Indexer?@S。。只需通过len(arr)更改len(arr)-1,您将得到一个索引器(除非arr是空数组,否则在这种情况下,for循环将永远不会执行)。如果数组的大小为3,则最后一个元素位于索引2处,但最后一次迭代将尝试访问索引3处的数组(arr[i+1])