使用n个相同的术语填充Python中的列表

时间:2016-12-02 13:07:16

标签: python list

我想用尽可能多的下划线填充列表,就像一个单词中有字母一样。我可以使用循环,例如:

for i in range(len(word)):

使用下划线填充列表,但感觉编码非常糟糕。是否有更好/更高级别的替代方案?

3 个答案:

答案 0 :(得分:2)

您需要将单个下划线list乘以单词的长度。例如,将列表与int 10相乘会得到:

>>> ['_'] * 10
['_', '_', '_', '_', '_', '_', '_', '_', '_', '_']

要查找单词的长度,请使用len()函数:

  

返回对象的长度(项目数)。参数可以是序列(例如字符串,字节,元组,列表或范围)或集合(例如字典,集合或冻结集)。

例如:

>>> len('Hello')
5

因此,您的最终代码可以写成:

>>> ['_'] * len('Hello')
['_', '_', '_', '_', '_']

答案 1 :(得分:2)

您可以使用

>>> s = """ <div class="cover"> <div class="cover-image-container"> <div class="cover-outer-align"> <div class="cover-inner-align"> <img alt="Kate Mobile Lite" class="cover-image" data-cover-large="" data-cover-small="" src="" aria-hidden="true"> </div> </div> </div> <a class="card-click-target" href="/s/kate_new_6" aria-label=" Kate Mobile Lite "> <span class="movies preordered-overlay-container id-preordered-overlay-container" style="display:none"> <span class="preordered-label">Предзаказ</span> </span> <span class="preview-overlay-container"> </span> </a> </div> <div class="cover"> <div class="cover-image-container"> <div class="cover-outer-align"> <div class="cover-inner-align"> <img alt="Kate Mobile Lite" class="cover-image" data-cover-large="" data-cover-small="" src="" aria-hidden="true"> </div> </div> </div> <a class="card-click-target" href="/s/kate_new_6" aria-label=" Kate Mobile Lite "> <span class="movies preordered-overlay-container id-preordered-overlay-container" style="display:none"> <span class="preordered-label">Предзаказ</span> </span> <span class="preview-overlay-container"> </span> </a> </div>""" >>> sp = BeautifulSoup(s) >>> sp.select(".cover > a.card-click-target") [<a aria-label=" Kate Mobile Lite " class="card-click-target" href="/s/kate_new_6"> <span class="movies preordered-overlay-container id-preordered-overlay-container" style="display:none"> <span class="preordered-label">?????????</span> </span> <span class="preview-overlay-container"> </span> </a>, <a aria-label=" Kate Mobile Lite " class="card-click-target" href="/s/kate_new_6"> <span class="movies preordered-overlay-container id-preordered-overlay-container" style="display:none"> <span class="preordered-label">?????????</span> </span> <span class="preview-overlay-container"> </span> </a>] >>> len(sp.select(".cover > a.card-click-target")) 2

将列表乘以数字会产生一个新列表,其中元素重复多次。

答案 2 :(得分:0)

一种简单的方法是分割字符串并使用len()乘以&#34; _&#34;:

st = "infidel niemcy said God is kill"
print [ "_"*len(word) for word in st.split()]