Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/asp.net-core/3.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_Arrays_Function_Loops_Conditional Statements - Fatal编程技术网

Python 无背对背重复项的函数到数组

Python 无背对背重复项的函数到数组,python,arrays,function,loops,conditional-statements,Python,Arrays,Function,Loops,Conditional Statements,我想使用一个函数,它接受数字或字母的字符串序列,并在数组中返回这些值,没有背对背的重复项,但可以有重复项,只是不能背对背 def unique_in_order(iterable): iterable = list(iterable) changed = [] for i in range(len(iterable)): if (iterable[i] != iterable[i+1]) : changed.append(itera

我想使用一个函数,它接受数字或字母的字符串序列,并在数组中返回这些值,没有背对背的重复项,但可以有重复项,只是不能背对背

def unique_in_order(iterable):
    iterable = list(iterable)
    changed = []
    for i in range(len(iterable)):
        if (iterable[i] != iterable[i+1]) :
            changed.append(iterable[i])
        break;
    return changed

通过对您的代码进行非常小的更改,我们可以非常轻松、紧凑地完成这项工作:

def unique_in_order(iterable):
    changed = []
    before = None
    for char in iterable:
        if before != char:
            before = char
            changed.append(char)
    return changed

x = "122333444455555666666777777788888888999999999"
z = "Mississippi"
print(unique_in_order(x))
print(unique_in_order(z))
输出:

['1', '2', '3', '4', '5', '6', '7', '8', '9']
['M', 'i', 's', 'i', 's', 'i', 'p', 'i']

由于您只希望函数得到一个字符串,因此我们可以假设,当我们对它进行迭代时,与
None
的比较永远不会是
True
。这会将新字符设置为
之前的

这只返回序列中的第一个值,但不会循环返回并获取其余值。您能否提供一个示例输入和预期输出?