“在r.text.split(“ \ n”)中以l换l”是什么意思?

时间:2020-02-21 02:53:24

标签: 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.split("\n")].index(True)-1

表示。

任何建议将不胜感激。

2 个答案:

答案 0 :(得分:1)

请考虑以下内容:

import pygame
import random

# --- constants --- (UPPER_CASE_NAMES)

WHITE = (255, 255, 255)
GREEN = (0, 150, 0)
RED   = (255, 0, 0)
GRAY  = (140, 140, 140)
BLACK = (0, 0, 0)

FPS = 25 # 144

# --- functions ---

# empty

# --- main ---

pygame.init()
screen = pygame.display.set_mode((1300, 700))

# - objects -

button01 = dict()
button01['image_normal'] = pygame.surface.Surface((100,100))#
button01['image_normal'].fill(GRAY)
#button01['image_normal'] = pygame.image.load('button_100.png')
#button01['image_normal'] = pygame.transform.scale(button01['image_normal'], (100, 100))
button01['image_hovered'] = pygame.surface.Surface((100,100))
button01['image_hovered'].fill(GREEN)
#button01['image_hovered'] = pygame.image.load('button_100hovered.png')
#button01['image_hovered'] = pygame.transform.scale(button02['image_hovered'], (100, 100))
button01['image_clicked'] = pygame.surface.Surface((100,100))
button01['image_clicked'].fill(RED)
#button01['image_clicked'] = pygame.image.load('button_100clicked.png')
#button01['image_clicked'] = pygame.transform.scale(button02['image_clicked'], (100, 100))
button01['state'] = 'normal'
button01['image'] = button01['image_normal']
button01['rect'] = button01['image'].get_rect(center=(630, 400))

plus_image = dict()
plus_image['image'] = pygame.surface.Surface((30, 30))
plus_image['image'].fill(BLACK)
plus_image['rect'] = plus_image['image'].get_rect()
plus_image['state'] = 'hidden'
#screen.blit(buttonPlusImage, [random.randrange(560, 680), random.randrange(330, 450)])

# - other -

click_number = 0

# - mainloop -

mainloop = True
clock = pygame.time.Clock()

while mainloop:

    pygame.display.flip()
    clock.tick(FPS)
    screen.fill(WHITE)

    # draw elements

    screen.blit(button01['image'], button01['rect'])
    if plus_image['state'] == 'displayed':
        screen.blit(plus_image['image'], plus_image['rect'])

    # check collisions and clicks

    if not button01['rect'].collidepoint(pygame.mouse.get_pos()):
        button01['state'] = 'normal'
        button01['image'] = button01['image_normal']
    elif pygame.mouse.get_pressed()[0]:
        button01['state'] = 'clicked'
        button01['image'] = button01['image_clicked']
    else:
        button01['state'] = 'hovered'
        button01['image'] = button01['image_hovered']

    #if button01['state'] == 'clicked':
    #    plus_image['rect'].center = [random.randrange(560, 680), random.randrange(330, 450)]
    #    plus_image['state'] = 'displayed'
    #else:
    #    plus_image['state'] = 'hidden'

    # other events

    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            mainloop = False
        if event.type == pygame.KEYDOWN:
            if event.key == pygame.K_ESCAPE:
                mainloop = False
        if event.type == pygame.MOUSEBUTTONDOWN:
            #if button01['state'] == 'hovered':
            if button01['rect'].collidepoint(event.pos):
                click_number += 1
                print('click_number:', click_number)
                plus_image['rect'].center = [random.randrange(560, 680), random.randrange(330, 450)]
                plus_image['state'] = 'displayed'
                button01['rect'].center = [random.randrange(560, 680), random.randrange(330, 450)]
        if event.type == pygame.MOUSEBUTTONUP:
            plus_image['state'] = 'hidden'

# - end -            

pygame.quit()
quit()

输出:

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 行是一个列表理解,其等效的基本python代码如下:

["Index" in l for l in r.split("\n")]

输出:

final_list = []
for l in r.split("\n"):
    final_list.append("Index" in l)
print(final_list)

答案 1 :(得分:0)

i = ["Index" in l for l in r.text.split("\n")].index(True) - 1

等效于:

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行恰好在其中带有“索引”的行之前。

我们将其分为几部分:

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" in lineTrue,否则为False。因此,["Index" in l for l in r.text.split("\n")]是一个布尔值列表,指示每行是否包含单词“ Index”:

[False, False, False, True, False, False]

string.index(value)模式返回包含value的列表的第一个索引(从0开始计数)。因此,i = ["Index" in l for l in r.text.split("\n")].index(True)是包含单词“ Index”的第一行的索引:

3

最后,我们减去1得到前面的行。因此,["Index" in l for l in r.text.split("\n")].index(True) - 1

2