Python的最后一次迭代有没有简单的方法来找到for循环Python中的最后一次迭代?我只想将列表转换为CSV。在For循环
在For循环
回答
到一个列表转换为CSV,使用join
-function:
>>> lst = [1,2,3,4]
>>> ",".join(str(item) for item in lst)
"1,2,3,4"
如果列表中已经包含字符串只,你只是做",".join(l)
。
这将不能正确转义包含值“”对于使用csv模块 – 2011-03-08 10:40:09
不正是你想要的:
>>> for i in range(5):
print(i)
else:
print("Last i is",i)
0
1
2
3
4
Last i is 4
编辑:有csv
模块中的标准库,或者干脆','.join(LIST)
'for'的实际答案'else'只有在不通过迭代结束时退出循环'break' – 2011-03-08 10:28:34
运行我不跨施工之前。有趣。 – neil 2011-03-08 11:15:09
实际上当for
环路蟒蛇结束,它必然是名仍然可以访问并绑定到其最后的值:
for i in range(10):
if i == 3:
break
print i # prints 3
我用这一招用with
,如:
with Timer() as T:
pass # do something
print T.format() # prints 0.34 seconds
要转换列表到csv可以使用csv
模块:
import csv
list_of_lists = ["nf", [1,2]]
with open('file', 'wb') as f:
csv.writer(f).writerows(list_of_lists)
的'file'
文件将是:
n,f
1,2
你最好的解决办法可能是使用csv模块,与其他地方一样建议。然而,要回答你的问题是说:
方案1:通过使用枚举()
for i, value in enumerate(my_list):
print value,
if i < len(my_list)-1:
print ", followed by"
选项2算自己的方式:外循环处理的终值(my_list[-1]
)
for value in my_list[:-1]:
print value, ", followed by"
print my_list[-1]
- 1. for循环for循环? - Javascript
- 2. For循环在Javascript中的for循环
- 3. 在for循环
- 4. 在For循环
- 5. 在for循环
- 6. 在for循环
- 7. For循环循环
- 8. For循环for循环:摆锤建模
- 9. linq for for循环内foreach循环
- 10. for-in循环到for循环或forEach
- 11. For循环更换:For循环滤镜
- 12. for循环里面for循环
- 13. 使用数组for循环for循环
- 14. 睡在for循环
- 15. addView在for循环
- 16. for循环在as3
- 17. Object.defineProperty在for循环
- 18. 睡在for循环
- 19. 击:在for循环
- 20. For循环在#define
- 21. EXC_BAD_ACCESS for for循环
- 22. EXC_BAD_ACCESS for for循环
- 23. Javascript:For循环for循环
- 24. For循环到While循环
- 25. For循环vs While循环
- 26. For循环vs Foreach循环
- 27. for循环while循环
- 28. set循环for循环?
- 29. es6 for循环不循环
- 30. For循环C#不循环
但是,也许如果你解释你的实际问题,我们可以建议一个替代解决方案? – 2011-03-08 10:17:03
我不知道标准的CSV模块可以解决你的问题的另一种方式。 – 2011-03-08 10:38:27
我不知道为什么没有答复这个问题的回答居然是...... – 2rs2ts 2013-05-30 15:45:17