datasci-info / AG101

0 stars 0 forks source link

一次寫入.write() #2

Closed anniehuang921 closed 9 years ago

anniehuang921 commented 9 years ago

原本:

my_list = [i**2 for i in range(1,11)]
my_file = open("output.txt", "r+")
for x in my_list:
    my_file.write(str(x)+ "\n" )#問題點
my_file.close()

嘗試:

my_list = [i**2 for i in range(1,11)]
my_file = open("output.txt", "r+")
my_file.write(str(x)+ "\n" for x in my_list)#
my_file.close()

不過這樣跑不出來....

c3h3 commented 9 years ago

因為 .... 他不知道

str(x)+ "\n" for x in my_list

這個是甚磨?

c3h3 commented 9 years ago

可以換成:

my_file.write("\n".join(my_list))
anniehuang921 commented 9 years ago

中間直接改會error:

my_list = [i**2 for i in range(1,11)]
my_file = open("output.txt", "w")
my_file.write("\n".join(my_list)) #
my_file.close()

TypeError: sequence item 0: expected str instance, int found

後來換成:

my_list = [i**2 for i in range(1,11)]
my_file = open("output.txt", "w")
mylist=list(map(str,my_list)) #
my_file.write("\n".join(mylist)) #
my_file.close()

就可以了~~ ps. In Py3