简体   繁体   English

将列表转换为字符串列表

[英]Convert a list into a list of strings

In Python, I have this list:在 Python 中,我有这个列表:

[(0, 0, 0), (0, 0, 1), (0, 1, 0), (0, 1, 1), (1, 0, 0), (1, 0, 1), (1, 1, 0), (1, 1, 1)]

and I want to convert it into a list of strings, like:我想将其转换为字符串列表,例如:

['000', '001', '010', '011', '100', '101', '110', '111']

This was my attempt:这是我的尝试:

val = [0,1]

['{x}{y}{z}'.format(x=x,y=y,z=z) for x in val for y in val for z in val]

But in some cases, the length of the string eg'001' may be variable (eg '01101') so it is frustrating editing this part '{x}{y}{z}'.format(x=x,y=y,z=z) each time但在某些情况下,字符串 eg'001' 的长度可能是可变的(例如 '01101'),因此编辑这部分'{x}{y}{z}'.format(x=x,y=y,z=z)每次

How can I do that?我怎样才能做到这一点?

Using for loops and concatenation:使用 for 循环和串联:

arr1 = [(0, 0, 0), (0, 0, 1), (0, 1, 0), (0, 1, 1), (1, 0, 0), (1, 0, 1), (1, 1, 0), (1, 1, 1)]

arr2 = []
for ind in range(len(arr1)):
    arr2.append("")
    for n in arr1[ind]:
        arr2[ind] += str(n)

print(arr2)

While this is a very simple and readable approach, there are other ways to do this that take up less space and have slightly more complex implementations, such as @Olvin Roght's solution .虽然这是一种非常简单易读的方法,但还有其他方法可以做到这一点,它们占用的空间更少,实现稍微复杂一些,例如@Olvin Roght 的解决方案

Here's the more simplifier version这是更简单的版本

a=[(0, 0, 0), (0, 0, 1), (0, 1, 0), (0, 1, 1), (1, 0, 0), (1, 0, 1), (1, 1, 0), (1, 1, 1)]
b=[]
for i in a:
    c=str(i)
    c=c.replace("(","")
    c=c.replace(")","")
    c=c.replace(",","")
    b.append(c)
print(b)

This would give you the exact same output as of @Aniketh Malyala 's answer这将为您提供与@Aniketh Malyala 的答案完全相同的输出

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

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