问题描述
我正在读取此CSV文件并将其值添加到班级列表中。您能解释一下如何使用剥离和拆分功能吗?
ba = []
for line in cvsfile:
j = line.split(',')
num,f,s,b = [i.strip() for i in j]
name = A(num,b)
ba.append(name)
我对这部分感到困惑。
j = line.split(',')
num,b = [i.strip() for i in j]
顺便说一句,我的班级名称是A。
请解释。提前致谢。对不起,英语不是我的母语。
解决方法
一个CSV文件具有用逗号分隔的值,并且程序正在逐行读取文件。考虑以下示例
subItem
现在,使用line = 'Val1,Val2,Val3' # consider this is a line in the CSV file
将在逗号处分割行并返回分割后的值的列表。
在j = line.split(',')
处拆分line
时,您将得到一个等于,
的列表,该列表现在将分配给['Val1','Val2','Val3']
。
j
方法将从字符串中删除任何结尾或开头的空格。例如,
.strip()
s = ' hello '
t = s.strip()
# now t is just equal to the string 'hello' without any spaces
正在创建[i.strip() for i in j]
中所有值的列表,但是从值中删除了所有空格。
j
只是将列表中的值分配给num,s,f和b。
示例
num,s,f,b = [i.strip() for i in j]
,
我的朋友Amtthias提到了列表理解。