Python 什么是;在l中代表l在r.text.split(“\n”中);什么意思?
我看到一个使用request.post下载网站的示例代码,例如:Python 什么是;在l中代表l在r.text.split(“\n”中);什么意思?,python,Python,我看到一个使用request.post下载网站的示例代码,例如: r = requests.post('https://xxxxxxxx) 然后重新排列内容: df = pd.read_csv(StringIO(r.text.replace("=", "")), header=["Index" in l for l in r.text.split("\n")].index(True)-1) 我不明白 ["Index" in l for l in r.text.spl
r = requests.post('https://xxxxxxxx)
然后重新排列内容:
df = pd.read_csv(StringIO(r.text.replace("=", "")),
header=["Index" in l for l in r.text.split("\n")].index(True)-1)
我不明白
["Index" in l for l in r.text.split("\n")].index(True)-1
意味着
如果您有任何建议,我们将不胜感激。请考虑以下几点:
r = '''
'hello there'
'Index'
'dummy'
'''
print(r)
# the following line returns a list with 'True' or 'False'
print(["Index" in l for l in r.split("\n")])
# the following line will find out the index where 'True' is found
print(["Index" in l for l in r.split("\n")].index(True))
# the following line with reduce '-1' from the index where 'True' is found
print(["Index" in l for l in r.split("\n")].index(True) - 1)
输出:
"\n'hello there'\n'Index'\n'dummy'\n"
[False, False, True, False, False]
2
1
[False, False, True, False, False]
行[“Index”在l中表示l在r.split(“\n”)]
是一个列表理解,其等效的基本python代码如下所示:
final_list = []
for l in r.split("\n"):
final_list.append("Index" in l)
print(final_list)
输出:
"\n'hello there'\n'Index'\n'dummy'\n"
[False, False, True, False, False]
2
1
[False, False, True, False, False]
相当于:
i = [
("Index" in line)
for line in r.text.split("\n")
].index(True) - 1
上述设置将i
设置为行号(从0开始计数),正好位于包含单词“Index”的第一行之前
例如,如果text
是:
0 From: Jane.Doe@example.com
1 To: Jon.Doe@example.com
2 Subject: Foo bar
3 Index: abcd
4 Comment: Hello, World
5 ...
然后是i=2
,因为第2行正好位于包含“Index”的行之前
让我们把它分成几个部分:
r.text
是下载网页中的文本:
'''0 From: Jane.Doe@example.com
1 To: Jon.Doe@example.com
2 Subject: Foo bar
3 Index: abcd
4 Comment: Hello, World
5 ...'''
r.text.split(“\n”)
是作为字符串列表的文本行:
[
'0 From: Jane.Doe@example.com',
'1 To: Jon.Doe@example.com',
'2 Subject: Foo bar',
'3 Index: abcd',
'4 Comment: Hello, World',
'5 ...'
]
如果行中有“Index”一词,则第
行中的“Index”为True
,否则为False
。因此,[“Index”在l中表示l在r.text.split(“\n”)]
是一个布尔值列表,指示每行是否包含单词“Index”:
string.index(value)
模式返回包含value
的列表的第一个索引(从0开始计数)。因此,i=[“Index”在l中表示r.text.split(“\n”)]中的l。Index(True)
是包含单词“Index”的第一行的索引:
最后,我们减去1得到前面的行。因此,[“Index”在l中代表l在r.text.split(“\n”)].Index(True)-1
:
2
中的“Index”是一个布尔表达式,询问字符串中的“Index”
是否位于变量l所引用的对象中[“Index”在l中表示l在[“line one”,“line two”,“Index”,“line four”]]
就是“列表理解”所做的事情。您将得到一个True和False'的列表,可以显示理解在r.split('\n')中作为l的for循环的外观:
来说明如何理解理解。
2