有关 Python 的列表推导式
by iamjing66
Python 列表推导式
最近一个月对接手的 Totnado 服务项目进行了比较大的一个改版(屎山翻修)比较多的用到了列表推导式和字符串的 join() 方法, 故此记录
这篇blog主要的来由是因为在 StackOverflow 上碰到一个拿手(简单)的问题
Is there a way to write a ‘list of lists’ to a .txt file in a certain format
这个问题主要是要对一个列表进行想要的排序和字符穿插后写入文件
# 有这样一个列表
a_list = [['Hi', 500], ['Bye', 500.0, 100, 900, 600], ['Great', 456, 700.0, 600], ["Yay", 200, 350.0], ["Ok", 200, 300, 400.0]]
他想要写入文件的样式是这样的
Hi 500
Bye 500.0,100,900,600
Great 246,700.0,600
Yay 200,350.0
Ok 200,300,400.0
可以看到是想要把二级列表中的第一项作为第一列,同时使用空格隔开第二列,第二列中使用,进行分割
先来模仿一下屎山的做法
# 通过两个遍历 获取到第一列的信息 和拼装第二列信息
a_list = [['Hi', 500], ['Bye', 500.0, 100, 900, 600], ['Great', 456, 700.0, 600], ["Yay", 200, 350.0], ["Ok", 200, 300, 400.0]]
t = open("a.txt", "w")
for i in a_list:
s1 = i[0]
s2 = ""
for j in i:
if s2 == "":
s2 = str(j)
else:
s2 = s2 + "," + str(j)
# 完成对写入行的拼接
s1 = s1 + " " + s2 + "\n"
t.write(s1)
但是这种写法不符合 Zen of Python
所以我改为了使用列表推导式和join()
a_list = [['Hi', 500], ['Bye', 500.0, 100, 900, 600], ['Great', 456, 700.0, 600], ["Yay", 200, 350.0], ["Ok", 200, 300, 400.0]]
t = open("a.txt", "w")
for i in a_list:
t.writelines(i[0] + " " + ",".join(list(map(str, i[1:])))+"\n")
# 推导式方案
# t.writelines(i[0] + " " + ","join([str(j) for j in i[1:] + "\n")
11月4日17:22:29 发生了什么??

就在我还在写这个blog时,我的最佳答案被取消了,然后我的答案输给了这个
alist = [['Hi', 500], ['Bye', 500.0, 100, 900, 600], ['Great', 456, 700.0, 600], ["Yay", 200, 350.0], ["Ok", 200, 300, 400.0]]
fn = "filename.txt"
mode = "w"
with open(fn, mode) as h: # file handle is auto-close
for v in alist:
h.write(v[0] + " ")
j = 1
while j < len(v):
if len(v) - 1 == j:
h.write(str(v[j])) # don't write a comma if this is the last item in the list
else:
h.write(str(v[j]) + ",")
j += 1 # increment j to visit each item in the list
h.write("\n")
我不懂但是我大受震撼 :-(
但是我还是觉得我的方法更好:p