将列表转回字符串python

时间:2018-11-09 02:06:01

标签: python

第一个函数能够分隔字符串的每个字母并列出该字母出现的次数。例如:

print(rlencode("Hello!"))
[('H', 1), ('e', 1), ('l', 2), ('o', 1), ('!', 1)]

如何获取rldecode(rle):执行rlencode(s)的完全相反的过程,以便rldecode(rlencode(x)) == x返回True

def rlencode(s):
    """
    signature: str -> list(tuple(str, int))
    """
    string=[]
    count=1
    for i in range(1,len(s)):
        if s[i] == s[i-1]:
            count += 1
        else:
            string.append((s[i-1], count))
            count=1
        if i == len(s)-1:
            string.append((s[i], count))
    return string



def rldecode(rle):
    """
    #signature: list(tuple(str, int)) -> str
    #"""
    string=" "
    count=1
    for i in rle:
        if i == rle:
            string += i
    return string

5 个答案:

答案 0 :(得分:1)

您可以使用以下事实:将字符串乘以数字以重复它,并使用`''.join()将列表中的元素组合在一起。

为显示字符串乘法的效果,我将"a"乘以5

"a"*5 #'aaaaa'

运用理解力会给您

str = [char[0]*char[1] for char in rle] #['H', 'e', 'll', 'o', '!']

然后添加''.join(),您就会得到答案。

l = [('H', 1), ('e', 1), ('l', 2), ('o', 1), ('!', 1)]
str = ''.join(char[0]*char[1] for char in rle) #'Hello!'

所以您的功能应该是

def rldecode(rle):
    """
    signature: list(tuple(str, int)) -> str
    """
    return ''.join(char[0]*char[1] for char in rle) 

此外,如果您想使自己的rlencode更加整洁,可以使用enumerate帮助您将其保持在字符串中的位置并检查是否即将击中新字符或字符串结尾。您只需要在每个循环上增加计数器。

def rlencode(s):

    output = []
    count = 0

    for i, char in enumerate(s):

        count += 1

        if (i == (len(s)-1)) or (char != s[i+1]):
            output.append((char, count))
            count = 0

    return output

答案 1 :(得分:0)

使用join

       if (lblCookieInventory.Text < numCookiesSold.Value)
        {

            // subtract item sold
            cs.CookieInventory = cs.CookieInventory - System.Convert.ToInt32(numCookiesSold.Value);

            // calculate invenotry value
            cs.CookieInventoryPrice = cs.CookieInventory * cs.CookiePrice;

            // return to list
            CookieScout[index] = cs;

            //re-display
            DisplayCookie();

            // clear number sold
            numCookiesSold.Value = 0;
        }
        // Update datafile
        UpdateCookieTextFile();
    }

您还可以将列表推导用于初始功能。

答案 2 :(得分:0)

您可以使用collections.Counter.elements()

from collections import Counter
l = [('H', 1), ('e', 1), ('l', 2), ('o', 1), ('!', 1)]
print(''.join(Counter(dict(l)).elements()))

这将输出:

Hello!

答案 3 :(得分:0)

一种简单易读的解决方案是遍历rlencode返回的列表中的所有元组,然后像这样从每个字母(及其频率)构造一个新字符串:

def rldecode(rle):
    string = ''
    for letter, n in rle:
        string += letter*n
    return string

答案 4 :(得分:-1)

一个简单易懂的答案,也说明了问题的排序:

V

我改编自@Brian Cohan发布的答案

应注意,如果def rlencode(s): """ signature: str -> list(tuple(str, int, list(int))) """ result=[] frequency=1 for i in range(len(s)): letters = [item[0] for item in result] if s[i] in letters: idx = letters.index(s[i]) frequency=result[idx][1] frequency+=1 positions= result[idx][2] positions.append(i) result[idx] = (s[i],count,lst) else: result.append((s[i],1,[i])) return result def rldecode(rle): """ #signature: list(tuple(str, int, list(int))) -> str #""" frequencies = [i[1] for i in rle] total_length = sum(frequencies) char_list=[None]*total_length for c in rle: for pos in c[2]: char_list[pos] = c[0] return "".join(char_list) text = "This is a lot of text where ordering matters" encoded = rlencode(text) print(encoded) decoded = rldecode(encoded) print(decoded) 的增长确实很长,如this SO post所述,答案是在计算上昂贵的,因为.index()