Python 将列表中的元素转化为字符串

colors = ['red', 'blue', 'yellow', 12, 3.14]
str1 = str(colors)[1:-1]
str1

>> "'red', 'blue', 'yellow', 12, 3.14"

这种方式,会将每一个元素拼到字符串中,从另一个角度看,他只是把中括号替换成了引号。

colors = ['red', 'blue', 'yellow'] 
str1 = ",".join(colors)
str1 

>> 'red,blue,yellow'

这种方式,将列表中的每一个字符串类型的元素取出来,拼成一个字符串。

注意这种方式只能操作字符串,像下面这种,则会报错,join 只接受 str 类型参数

colors = ['red', 'blue', 'yellow', 12, 3.14] 
str1 = ",".join(colors)
>> 
Traceback (most recent call last):
  File "<input>", line 1, in <module>
TypeError: sequence item 3: expected str instance, int found

简单的字符串转列表

str1 = "hi hello world"
print(str1.split(" "))

['hi', 'hello', 'world']

多维(规则或不规则维)数组

origin = [["x1", "y1", "z1"], ["x2", "y2", "z2"]]

# 二维
target = ",".join([two for one in origin for two in one])
print(target)

test1 = [["x1", "y1", "z1"], ["x2", "y2", "z2"]]
test2 = [["x1", "y1", "z1"], ["x2", "y2", "z2"], ["2", "3"], ["5"], "8"]
test3 = [["1",[2,3,4,5],[6,7,[8]]],["9","10"],["11","12"],13,["14",[15,16,[17],[18,"19",20],[1]]]]
# 多维度()
def multi_list_iter(origin_list, target_list):
    for item in origin_list:
        if not type(item) == list:
            target_list.append(str(item))
        else:
            multi_list_iter(item, target_list)
    return target_list

target_list = []
multi_list_iter(test1, target_list)
print(",".join(target_list))
target_list = []
multi_list_iter(test2, target_list)
print(",".join(target_list))
target_list = []
multi_list_iter(test3, target_list)
print(",".join(target_list))

 

评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值