简体   繁体   English

如何在保留 Python 中元素的原始顺序的同时返回字符串中的项目列表

[英]How to return a list of items in a string while preserving the original order of elements in Python

I am stuck on this coding challenge from Codewars:我被 Codewars 的这个编码挑战困住了:

"Implement the function unique_in_order which takes as argument a sequence and returns a list of items without any elements with the same value next to each other and preserving the original order of elements." “实现函数 unique_in_order ,它将一个序列作为参数,并返回一个项目列表,其中没有任何具有相同值的元素彼此相邻并保留元素的原始顺序。”

"For example: “例如:

unique_in_order('AAAABBBCCDAABBB') == ['A', 'B', 'C', 'D', 'A', 'B']
unique_in_order('ABBCcAD')         == ['A', 'B', 'C', 'c', 'A', 'D']
unique_in_order([1,2,2,3,3])       == [1,2,3]

"

This is how far I was able to come so far:这是到目前为止我能够走多远:

def unique_in_order(iterable):
    iterable= list(set(iterable))

    return sorted(iterable)

Which gets me an output of:这让我得到一个输出:

['A', 'B', 'C', 'D']

For the following input:对于以下输入:

['AAAABBBCCDAABBB'] 

instead of the desired output of:而不是所需的输出:

['A', 'B', 'C', 'D', 'A', 'B'] 

I appreciate your help.我感谢您的帮助。

set creates an object with each element in the list occuring only once. set创建一个对象,列表中的每个元素只出现一次。 Instead of a built in function you're going to have to write something yourself.您将不得不自己编写一些东西,而不是内置函数。 How to do this?这该怎么做?

First, create the input and a list that willstore your result:首先,创建输入和一个将存储结果的列表:

input_word = 'aabbbaaa'
output_list = []

Now, what we will do is loop over the word, and every new letter we append.现在,我们要做的是循环遍历单词和我们附加的每个新字母。 So we need to track what the "current" letter is:所以我们需要跟踪“当前”字母是什么:

current_letter = None

At first we set it to None because we have no current letter yet.起初我们将它设置为 None 因为我们还没有当前的字母。 Now we loop over the word:现在我们循环这个词:

for letter in input_word:
    if letter != current_letter:
        output_list.append(letter)
        current_letter = letter
print(output_list)
>>> ['a', 'b', 'a']

The easiest way would be to do this:最简单的方法是这样做:

>>> string = "AAAABBBCCDAABBB"
>>> new_list = []
>>> for i in string:
...     if not new_list:
...             new_list.append(i)
...     elif new_list[-1] != i:
...             new_list.append(i)
...
>>> new_list
['A', 'B', 'C', 'D', 'A', 'B']

You can wrap this into a function if need be.如果需要,您可以将其包装到一个函数中。

You can do this easily with a list comprehension using zip and some nifty slicing.您可以使用zip和一些漂亮的切片通过列表理解轻松完成此操作。 It's basically the pairwise recipe without using itertools.它基本上是不使用 itertools 的成对配方。 If you want you can look that recipe up if you need it too.如果您愿意,也可以查看该食谱。

[it[0]] + [nc for c, nc in zip(it, it[1:]) if c != nc]

For clarity c is the current character nc is the next character in the pair.为清楚起见, c是当前字符nc是该对中的下一个字符。


>>> it = 'AAAABBBCCDAABBB'
>>> [it[0]] + [nc for c, nc in zip(it, it[1:]) if c != nc]
['A', 'B', 'C', 'D', 'A', 'B']

This can be shown as a standard for loop as well for more clarity:为了更清楚,这也可以显示为循环的标准:

result = [it[0]]
for c, nc in zip(iterable, iterable[1:]):
    if c != nc:
        result.append(nc)

You can try this.你可以试试这个。

Iterate through the string.遍历字符串。 Whenever ith element and ith+1 don't match add the ith element to list `res.每当第 i 个元素和i 个元素不匹配时,将第i 个元素添加到列表 `res.

def unique_order(_iter):
    if not _iter:
        return []
    res=[]
    for i in range(0,len(_iter)-1):
        if _iter[i]!=_iter[i+1]:
            res.append(_iter[i])
    res.append(_iter[-1])
    return res

unique_order('AAAABBBCCDAABBB') #output is ['A', 'B', 'C', 'D', 'A', 'B']

itertools.groupby() can be used here. itertools.groupby()可以在这里使用。

from itertools import groupby
def unique_order(_iter):
    return [k for k, g in groupby(_iter)] #'AAAABBBCCDAABBB'--> ['A', 'B', 'C', 'D', 'A', 'B']

You should use itertools.groupby .您应该使用itertools.groupby The behaviour you want is the same as the uniq command.您想要的行为与uniq命令相同。 As the doc says, groupby has a similar beahviour.正如文档所说, groupby有类似的行为。

>>> import itertools
>>> [k for k, _ in itertools.groupby('AAAABBBCCDAABBB')]
['A', 'B', 'C', 'D', 'A', 'B']
>>> 

This question describes a similar behaviour to yours.这个问题描述了与您类似的行为。

def unique_in_order(iterable):
    output = []
    letter = None
    for current in iterable:
        if current != letter:
            output.append(current)
            letter = current

    return output

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 在保留原始列表顺序的同时拆分列表中的字符串 - Split String In List While Preserving Original List Order 如何在保留原始顺序的同时在 Python 中加载 YAML 文件 - How to load a YAML file in Python while preserving the original order 反向链接列表,同时保留原始顺序 - Reverse a linked list while preserving the original order 从列表中删除项目,同时保留python3中的顺序 - Removing items from a list while preserving order in python3 如何在保留列表顺序的同时修改(而不是删除!)Python列表中的重复元素? - How can I modify (not remove!) duplicated elements in a Python list, while preserving their order? 反转字符串的顺序,同时保留字符串的原始内容 - Invert the order of a string, while preserving the original contents of the string 从大型 Python 列表中删除大量元素,同时保留元素的顺序 - Removing a lot of elements from a large Python list while preserving the order of elements 在保留元素顺序的同时,找到包含元素1…N的列表的K个子集 - Find K subsets of a list with elements 1…N while preserving the order of the elements 如何在保留订单的同时查询列表 - How to query list while preserving order 如何在保持参考原始 Python 的同时更改列表的顺序 - How to change the order of a list while keeping reference to the original Python
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM