Python中的逗号作用有格式化、不换行、去换行符、追加内容等等.比如'one' 'two' 'three' 'four'这是4组独立字符串,用,号来连接.
方法一:def count_pos(l): num = 0 for x in l: # 直接遍历数组就可以了,加了range反而错了. if x > 0: num += 1 print(num) s = input('input some number: ') l = eval(s) # 因为不会修改数列的内容,所以用tuple就可以,没必要转成list count_pos(l) 方法二:s = input('input some number: ') l = eval(s) print(count([x for x in l if x > 0])) # 一句话搞定,没必要写函数
区分元组和单个值返回元组,就不能被更改例如下面代码加一个逗号就是返回tuple了 def f():return 1,type(f())
# -*- coding: utf-8 -*-# 1.txt 改成你自己的文件 print [ map(int,line.strip().split()) for line in open('1.txt').readlines() if len(line.strip().split())>1]
(('sssss',), ('root',)) 和 ('sssss', 'root') 表示的东西不一样.'sssss', 有逗号表示的是 tuple, 而'sssss'只是字符串,所以(('sssss',), ('root',)) 是tuple 组成的tuple,('sssss', 'root') 是字符串组成的tuple.(('sssss',), ('root',)) 转成 (('sssss'), ('root')) t=(('sssss',), ('root',)) result=(j for i in t for j in i)
注意检查一定是英文逗号啊 中文逗号肯定要报错
读取open文件.然后read读取内容.用replace替换内容.write写回文件new__string = old__string.replace(' ', '_')
好像中用来分割 列表 字典的项,没其他意思 吧
这种情况会有引号引起来,所以直接使用就行也可以直接使用csv库
f = open('test.txt', 'r') #以读方式打开文件 result = list() for line in f.readlines(): #依次读取每行 line = line.strip() #去掉每行头尾空白 if not len(line) or line.startswith('#'): #判断是否是空行或注释行 continue #是的话,跳过不处理 result.append(line) #保存 print ','.join(result)