Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/304.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

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/python-3.x/16.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_Python 3.x - Fatal编程技术网

如何查找序列中的相邻对,python

如何查找序列中的相邻对,python,python,python-3.x,Python,Python 3.x,对于我的一个作业,我必须编写一个代码来查找序列中的相邻对。如果序列中没有对,则输出必须为无。可以是一个列表,字符串,等等。我只为一半的测试文件(真正的测试文件)编写了代码,但我在通过错误的测试文件时遇到了困难。我不确定我做错了什么,我想帮助完成这项任务。以下是我正在使用的代码: def neighboring_twins(xs): twins = False for i in range(len(xs)): for j in range(i+1,len(xs)):

对于我的一个作业,我必须编写一个代码来查找序列中的相邻对。如果序列中没有对,则输出必须为无。可以是一个列表,字符串,等等。我只为一半的测试文件(真正的测试文件)编写了代码,但我在通过错误的测试文件时遇到了困难。我不确定我做错了什么,我想帮助完成这项任务。以下是我正在使用的代码:

def neighboring_twins(xs):
    twins = False
    for i in range(len(xs)):
        for j in range(i+1,len(xs)):
            if xs[i] == xs[j]:
            twins = True
     return twins
样本输入:

xs = [1,1]
输出=
true

xs = [2,1,2]
输出=
False

xs = []

输出=
False
从第二项开始循环通过
xs
,并与前一项进行比较:

xs = []
def neighboring_twins(xs):
    for i in range(1, len(xs)):
        if xs[i] == xs[i-1]:
            return True
    return False

请修正你的缩进。我试图编辑,但我不知道哪一行属于哪一行。请提供示例输入和所需输出。这里不需要两个
for
循环。事实上,这是错误结果的一个原因。谢谢。我知道我做错了什么,你的代码比我做的更有意义。