【问题标题】:access list values with index python使用索引python访问列表值
【发布时间】:2020-11-18 19:59:58
【问题描述】:

所以,我遇到了一些非常有趣的事情。我用 .splitlines() 分割了一个字符串。 当我打印该列表时,它可以正常工作并以该形式输出值:['Freitag 24.11', '08:00']。 但是,如果我尝试通过索引访问该列表的任何值,例如list[0],它应该给我该列表的第一个值。在本例中为“Freitag 24.11”。

splittedParameters = tag.text.splitlines()
print(splittedParameters[0])

如前所述,如果我不使用索引 [0],它就可以正常工作并输出整个列表。但在带有索引的那种形式中,它说:“IndexError: list index out of range”

整个代码:

    from requests_html import HTMLSession

    startDate = None
    endDate = None
    summary = None
    date = ''
    splittedDate = ''

    url = 'ANY_URL'

    session = HTMLSession()
    r = session.get(url)
    r.html.render()

    aTags = r.html.find("a.ui-link")

    for tag in aTags:
        splittedParameters = tag.text.splitlines()
        print(splittedParameters[0])

【问题讨论】:

  • 执行splittedParameters = ['Freitag 24.11', '08:00']
  • 你能告诉我们tag.text.splitlines()在真实代码中的样子吗
  • 请说明 tag.text 包含什么
  • 您应该在某处有错字,我无法重现您的问题。我建议你单独做一个测试,像这样:repl.it/@alejomongua/IndigoFreeExam
  • tag.text 包含一个看起来像这样的字符串:'Montag 23.11\n09:10'

标签: string list split concatenation python-3.8


【解决方案1】:
splittedParameters

没有返回任何值,因为它没有给定任何值。

aTags 中没有文字

print(aTags)

>>> [<Element 'a' class=('logo', 'ui-link') href='index.php'>]

阅读您的评论后,我尝试了:

for tag in aTags:
    print(tag.text)
    splittedParameters = tag.text.splitlines()

我什么都没打印出来

【讨论】:

  • 你看到我上传的图片了吗?为什么它不起作用?
  • 你能把代码复制到问题中,或者告诉我splittedParameters 在真实代码中的样子,就像粘贴一样
  • print(type(splittedParameters)) 告诉我你得到了什么
  • 它说
  • 但是在for循环中我遍历了aTags并且在每个标签中都有属性文本,它是一个字符串,我也可以打印出来
【解决方案2】:

我发现了错误。 问题在于,在 for 循环的第一次运行中,列表“splittedParameters”为空。

    if len(splittedParameters) > 0:
        print(splittedParameters[0])

这会起作用。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-02-18
    • 2016-05-28
    • 1970-01-01
    • 1970-01-01
    • 2017-04-18
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多