简体   繁体   English

将列表转换为字符串列表python

[英]Convert a list to a string list python

I'm Python beginner can't get my head around. 我是Python初学者无法理解我的头脑。 How do I change for example a = [[1,2],[3,4],[5,6]] into "12\\n34\\n56" string format. 如何将例如a = [[1,2],[3,4],[5,6]] "12\\n34\\n56""12\\n34\\n56"字符串格式。

This is as far as i got but it goes into newline with each number. 这是我得到的,但它与每个数字进入换行符。

def change(a):
    c = ""
    for r in a:
        for b in r:
            c += str(b) + "\n"
    return c

but it goes into newline with each number 但是每个号码都会进入换行符

That's because you add the newline after each number instead of after each sublist r . 那是因为你在每个数字之后而不是在每个子列表r之后添加换行符。 If you want that instead, you should append the newline there: 如果你想要它,你应该在那里附加换行符:

c = ''
for r in a:
    for b in r:
        c += str(b)
    c += '\n'
return c

But note that appending to a string is very inefficient, as it ends up creating lots of intermediary strings. 但请注意,附加到字符串是非常低效的,因为它最终会创建大量的中间字符串。 Usually, you would create a list instead to which you append your string parts, and then finally join that list to convert it to a single string: 通常,您将创建一个列表,而不是您追加字符串部分,然后最终加入该列表以将其转换为单个字符串:

c = []
for r in a:
    for b in r:
        c.append(str(b))
    c.append('\n')
return ''.join(c)

And then, you can also use list expressions to make this shorter in multiple steps; 然后,您还可以使用列表表达式在多个步骤中缩短它们; first for the inner list: 首先是内部列表:

c = []
for r in a:
    c.extend([str(b) for b in r])
    c.append('\n')
return ''.join(c)

And you can join that list comprehension first: 您可以先加入该列表理解:

c = []
for r in a:
    c.append(''.join([str(b) for b in r]))
    c.append('\n')
return ''.join(c)

Then you can move the newline into the outer join, and make a new list comprehension for the outer list: 然后,您可以将换行符移动到外部联接中,并为外部列表创建新的列表解析:

c = [''.join([str(b) for b in r]) for r in a]
return '\n'.join(c)

And at that point, you can make it a one-liner too: 在那一点上,你也可以把它变成一个单行:

return '\n'.join([''.join([str(b) for b in r]) for r in a])

As Padraic pointed out in the comments, joining on the newline character will also prevent the string from having a trailing \\n which you would end up if you kept adding it in the loop. 正如Padraic在评论中指出的那样,加入换行字符也会阻止字符串有一个尾随\\n如果你继续在循环中添加它,你最终会结束。 Otherwise, you could have used str.rstrip('\\n') to get rid of it afterwards. 否则,您可以使用str.rstrip('\\n')来删除它。

Using str.join with generator expression : str.join生成器表达式一起使用:

>>> a = [[1,2], [3,4], [5,6]]
>>> '\n'.join(''.join(map(str, xs)) for xs in a)
'12\n34\n56'

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM