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))