【问题标题】:Making Python for loop with nested if statement more efficient使用嵌套 if 语句使 Python for 循环更高效
【发布时间】:2018-11-23 07:07:49
【问题描述】:

我有一个包含 1,000 个 URL 和公司名称的数据框,我需要将其转换为 HTML 链接并进行一些格式化。我写了一个函数,可以去列表和创建标签:

def linkcreate():
    if row['url'] == '####' or row['url'] == '#####':
        print('<span style="color: #293789!important; margin-bottom:0;">' + row['name'] + '</span>')
    else:
        print('<a href="' + row['url'] + '" target="_blank">' + row['name'] + '</a>')

if 语句 做了一些清理工作,因为有几十家公司没有网址。这些在df中表示为“####”和“#####”。对于这些,我添加了一个 span 标签 而不是 a 标签,并带有一些看起来像链接的样式。 else 语句只是根据 df 中的两列构造链接。

我想做的另一件事是将链接的一半放入,另一半放入 .下面是我的代码和解释:

# Calculates the middle point from the total count of rows in df
count = (int(data['url'].count()))/2
# Set counter to 0
counter = 0

for index, row in data.iterrows():
    counter = counter + 1
# Before the first <a> tag start the first section <div>
    if counter == 1:
        print('<div class="side-1">')
# If counter is less then or equals to the half point of rows in df build the links using the linkcreate()
    elif counter <= count:
        linkcreate()
# If counter is +1 from the half way point of rows add the closing </div> and start the second <div>
    elif counter == count + 1:
        print('</div>')
        print(' ')
        print('<div class="side-2">')
# If counter is greater then the half point of rows in df build the rest of the links using the linkcreate()
    elif counter > count:
        linkcreate()
# Closing </div> tag for the second set of links.
print('</div>')

此代码有效,但它是最有效的方法吗?

【问题讨论】:

  • 为什么要用print语句?
  • 你看this的答案了吗?
  • @Ben.T 我是 Python 新手。我想用一个真实的场景来练习。认为打印是合适的。我应该改用什么?
  • @user32185 谢谢。我去看看。
  • @user3088202 好的,但最后你想创建一个文件以供以后使用,我假设还是不特别?

标签: python python-3.x pandas


【解决方案1】:

为了更快,您可以先创建一个包含链接的列:

def linkcreate(row):
    if '####' in row['url']: # will catch both '####' and '#####'
        return '<span style="color: #293789!important; margin-bottom:0;">' + row['name'] + '</span>'
    else:
        return '<a href="' + row['url'] + '" target="_blank">' + row['name'] + '</a>'
df['link'] = df.apply(linkcreate,axis=1)

那么你说的打印不是你关心的:

print('<div class="side-1">')
print(df['link'][:count+1].to_string(header=None, index=False))
print('</div>')
print(' ')
print('<div class="side-2">')
print(df['link'][count+1:].to_string(header=None, index=False))
print('</div>')

您打印时没有循环一半的列链接

【讨论】:

  • 这太棒了!因此,如果我没看错,您将向 df 添加另一列,该列应用创建 url 的函数。在第二部分中,您正在打印该列。我唯一不清楚的是 [:count+1] / [count+1:]。您是否正在访问索引并限制选择的行数? [:count+1] = to 0 - half point and [count+1:] = half point to end?它如何确定一半在哪里?
  • @user3088202 实际上我添加了一个带有 url 的列。对于[:count+1] / [count+1:],您从头到尾都是正确的。但它并没有真正访问索引(因为索引不必是整数)但它是数量的一部分,有关切片的更多详细信息,请参见link。因此,对于一半,我使用了您的 count,它给出了您数据的一半大小,然后我将其切成一半
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2012-04-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多