<p>下面是我将如何实现您的代码:</p>
<pre><code>from collections import OrderedDict
def repeats(lst):
return [el for el in lst if lst.count(el) > 1]
def shorten(lst):
repeat_els = repeats(lst)
new_lst = [el for el in lst if el not in repeat_els]
repeats_str = '-'.join(repeat_els)
core_repeats = '-'.join(list(OrderedDict.fromkeys(repeat_els)))
repeat_times = repeats_str.count(core_repeats)
first_repeat_index = lst.index(repeat_els[0])
repeats_str = '({}) {}'.format(core_repeats, repeat_times)
new_lst.insert(first_repeat_index, repeats_str)
return ','.join(new_lst)
</code></pre>
<p>概述一下:上面的代码首先将重复和非重复元素分为两个单独的列表。然后将重复的元素格式化为正确的字符串格式,将格式化的字符串添加到非重复元素列表的正确位置,然后将整个非重复元素列表<code>','.join</code>合并在一起。你知道吗</p>
<p>下面是一个演示:</p>
<pre><code>>>> list1 = ["New York", "California", "Illinois",
... "Texas", "Illinois", "Texas", "Illinois",
... "Texas", "Illinois", "Texas", "Illinois",
... "Texas", "Indiana"]
>>>
>>> shorten(list1)
'New York,California,(Illinois-Texas) 5,Indiana'
>>>
>>> list2 = ["New York", "California", "Illinois",
... "Texas", "Indiana", "Ohio",
... "North Carolina", "Washington", "Illinois",
... "Texas", "Indiana", "Ohio",
... "North Carolina", "Washington", "Colorado",
... "Michigan"]
>>> shorten(list2)
'New York,California,(Illinois-Texas-Indiana-Ohio-North Carolina-Washington) 2,Colorado,Michigan'
>>>
</code></pre>