[英]Why do we use like this?
I am reading this CSV file and adding its value to a list of a class.我正在阅读此 CSV 文件并将其值添加到类列表中。 Can you kindly explain how is it possible to use the strip and split function like this?
你能解释一下如何使用这样的剥离和拆分功能吗?
ba = []
for line in cvsfile:
j = line.split(',')
num, f, s, b = [i.strip() for i in j]
name = A(num, f, s, b)
ba.append(name)
I am confused at this part.我对这部分感到困惑。
j = line.split(',')
num, f, s, b = [i.strip() for i in j]
By the way, my class name is A.顺便说一下,我的班级名称是 A。
Please explain.请解释。 Thanks in advance.
提前致谢。 Sorry for the language as English is not my first.
对不起,因为英语不是我的第一语言。
A CSV file has values separated by commas and the program is reading in the file line by line. CSV 文件的值以逗号分隔,程序正在逐行读取文件。 Consider the following example
考虑下面的例子
line = 'Val1,Val2,Val3' # consider this is a line in the CSV file
Now, using j = line.split(',')
will split the line at the commas and return back a list of the values splitted.现在,使用
j = line.split(',')
将在逗号处拆分行并返回拆分的值列表。
When you split line
at ,
, you get a list equal to ['Val1', 'Val2', 'Val3']
which will now be assigned to j
.当您在
,
['Val1', 'Val2', 'Val3']
line
时,
您会得到一个等于['Val1', 'Val2', 'Val3']
,现在将分配给j
。
The .strip()
method will remove any trailing or starting spaces from a string. .strip()
方法将从字符串中删除任何尾随或起始空格。 For example,例如,
s = ' hello '
t = s.strip()
# now t is just equal to the string 'hello' without any spaces
[i.strip() for i in j]
is creating a list of all values in j
, but all spaces are removed from the values. [i.strip() for i in j]
是创建在所有的值的列表j
,但所有的空格被从值除去。
num, s, f, b = [i.strip() for i in j]
is simply assigning the values inside the list to num, s, f and b. num, s, f, b = [i.strip() for i in j]
只是将列表中的值分配给 num、s、f 和 b。
Example,例子,
a, b, c, d = [1, 2, 3, 4]
# the above line assigns a to 1, b to 2, c to 3 and d to 4
我的朋友 Amtthias 提到它被称为列表理解。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.