回答此问题可获得 20 贡献值,回答如果被采纳可获得 50 分。
<p>我想通过告诉这两个元素重复了多少次来缩短一个包含重复元素的列表。你知道吗</p>
<pre><code>list1 = ["New York", "California", "Illinois", "Texas", "Illinois", "Texas", "Illinois", "Texas", "Illinois", "Texas", "Illinois", "Texas", "Indiana"]
repetitives = []
for num, element in enumerate(list1):
if element == list1[num - 2]:
repetitives.append(element)
core_repetitives = repetitives[0:2]
string_repetitives = ",".join(repetitives)
string_core_repetitives = ",".join(core_repetitives)
repetitives_times = string_repetitives.count(string_core_repetitives)
string_list1 = ",".join(list1)
print string_list1.replace(string_repetitives, "(" + "-".join(core_repetitives) + ") " + str(repetitives_times) + " times")
</code></pre>
<p>输出为:</p>
<pre><code>New York,California,(Illinois-Texas) 4 times,Illinois,Texas,Indiana
</code></pre>
<p>很明显,它错过了一个计数。你知道吗</p>
<p>问题是列表“repetitives”没有从“if element==list1[num-2]:”行中得到正确的部分。你知道吗</p>
<p>如何正确识别“伊利诺伊州-德克萨斯州”重复5次?你知道吗</p>
<p><strong>相关问题</p>
<p>上述问题有两个已知要素。但是如果重复部分是由未知数量的重复组成的呢?你知道吗</p>
<p>例如:</p>
<pre><code>list2 = ["New York", "California", "Illinois", "Texas", "Indiana", "Ohio", "North Carolina", "Washington", "Illinois", "Texas", "Indiana", "Ohio", "North Carolina", "Washington", "Colorado", "Michigan"]
</code></pre>
<p>如何分辨[“伊利诺伊州”、“德克萨斯州”、“印第安纳州”、“俄亥俄州”、“北卡罗来纳州”、“华盛顿州”]在这里重复两次?你知道吗</p>