检查列表中的元素是否在Django temp的另一个列表中

2024-03-28 10:18:03 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在列表中做一个for loop。对于这个列表中的每个元素,我想知道这个元素是否可以与另一个列表中的4个单词中的一个相同。你知道吗

以下是我的示例,以描述这种情况:

在我看来:

content = ['**Added**:\n', '* something (toto-544)\n', '\n', '**Changed**:\n', ...]

operations = ['Added', 'Changed', 'Fixed', 'INTERNAL']

从我的HTML文件:

{% for line in content %}
  {% if line in operations %}
    <tr class="table-subtitle">
      <td colspan="12">{{ line }}</td>
    </tr>
  {% else %}
    <tr class="table-value-content">
      <td colspan="12">{{ line }}</td>
    </tr>
  {% endif %}
{% endfor %}

它应该显示第一个line元素,与第二个不同(我在两个类之间更改了颜色)。因为line[0]operations而不是line[1]。你知道吗

你知道为什么我的for loop/if statement不起作用吗?你知道吗


Tags: inloop元素列表addedforifline
2条回答

正如所说,@shourav'Added''**Added**:\n'不是一回事。这是我的一个错误,因为我相信inicontains一样工作。你知道吗

这个检查对于模板来说有点复杂,但是您可以使用^{}函数在Python代码中轻松地实现它。 由于字符串较长,您可以检查操作是否是in字符串:

any(
    op.lower() in s.lower()
    for op in operations)

测试代码:

content = ['**Added**:\n', '* something (toto-544)\n', '\n', '**Changed**:\n',]
operations = ['Added', 'Changed', 'Fixed', 'INTERNAL']

for s in content:
    print()
    print('s:', repr(s))
    print('s in operations:', s in operations)
    print('custom check:   ', any(op.lower() in s.lower() for op in operations))

结果是:

s: '**Added**:\n'
s in operations: False
custom check:    True

s: '* something (toto-544)\n'
s in operations: False
custom check:    False

s: '\n'
s in operations: False
custom check:    False

s: '**Changed**:\n'
s in operations: False
custom check:    True

相关问题 更多 >