使用Python查找文件中列表中的重复次数

2024-09-19 20:38:07 发布

您现在位置:Python中文网/ 问答频道 /正文

我需要找出列表中一个条目连续重复的次数。例如,考虑以下文件

"hello hello [A B C]"
"my world [D C F L]"
"tick tock [A L]"

在这个文件中,C重复的次数是2
重复不算在内,因为它不是连续重复的。在

我不确定是否使用re,因为它不会告诉我它是否连续重复。会有帮助的。在


Tags: 文件rehello列表worldmy条目次数
3条回答

最简单的方法是使用re解析文件。在

可以工作的正则表达式:\[([A-Z]\s)+[A-Z]\]

然后用列表“list string”(又名[“[abc]”,“[fgr]”])将其转换为列表。在

对于“[ABC]”“ABC”的格式必须是这样的,因此删除每个空格和[]。在

converted_string_list = list(str_list)

因此,打印转换后的“字符串”列表将为“ADF”这样的字符串生成类似这样的列表:

^{pr2}$

然后合并所有列表并找到重复项。在

这是一个非常前卫的解决方案!我相信有更好的解决办法

当你把重复的东西放进一个列表中时,你可以对它们进行计数:

initial_length = len(my_list)
new_length = len(set(my_list))
duplicates = initial_length - new_length
def find_repeats_in_list(lines):
    # get lists from every line
    all_items = []
    for line in lines:
        open_bracket = line.index('[')
        close_bracket = line.index(']')
        items = line[open_bracket+1:close_bracket].split()
        all_items.append(items)

    # initialize dictionaries to hold consecutive counts
    counts = dict()
    final = dict()

    # seed counts with list from first line
    for item in all_items[0]:
        counts[item] = 1

    # check for first line list items in subsequent lines
    for items in all_items[1:]:
        for counted in counts:
            remove = []
            if counted not in items:      # not in current line, stop counting
                remove.append(counted)
                if counts[counted] > 1:   # but put in final if more than one
                    final[counted] = counts[counted]
        for item in remove:
            del counts[item]
        for item in items:                # now increment anything consecutive
            if item in counts:
                counts[item] += 1
    return final

相关问题 更多 >