【问题标题】:How to count repeated special characters in a url and append to list?如何计算 url 中重复的特殊字符并附加到列表中?
【发布时间】:2020-04-29 22:06:07
【问题描述】:

我有两个网站的列表,我想数“。”点和“-”连字符 它重复的次数,我想把它分配给空的 for 循环中每次迭代的列表。当我执行下面的代码时 计算点和连字符,但对于每次迭代,它的计数都是以前的 值并增加计数,如 [1,2,3,6,12...] 但我想存储 每个迭代值在列表中分开,如 [1,3,2,5....] 怎么办?

tdots=[]
tphen = []
dots = 0
phen = 0
named_url = ['www.facebook.com','yahoo.com/index-true']

for i in named_url:
    for j in i:
        if '.' in str(j):
            dots = dots + 1
            Dots = []
            Dots.append(dots)
        else:
            print('No more "."')
    tdots.append(sum(Dots))        
for i in named_url:
    for j in i:
        if '-' in str(j):
            phen = phen + 1
            Phen = []
            Phen.append(phen)
        else:
            print('No more "-"')
    tphen.append(sum(Phen))
print(tdots,'Dots')
print(tphen,'Hyphen')

【问题讨论】:

    标签: python-3.x for-loop


    【解决方案1】:

    试试这个:-

    dots = []
    phens = []
    named_url = ['www.facebook.com','yahoo.com/index-true']
    
    for name in named_url:
        dots.append(name.count('.'))
    
    for name in named_url:
        phens.append(name.count('-'))
    
    tdots = sum(dots)
    tphens = sum(phens)
    
    print(dots, phens, tdots, tphens)
    

    输出:-

    [2, 1]
    [0, 1]
    3
    1
    

    【讨论】:

    • 我的问题错了吗?我不知道为什么我得到否定 -1 我应该格式化我的问题吗?感谢您的回答,它有效。
    【解决方案2】:
    named_url = ['www.facebook.com','yahoo.com/index-true']
    dots_sum = []
    hyphens_sum = []
    
    dots = []
    hyphens = []
    for url in named_url:
        dots.append(url.count('.'))
        hyphens.append(url.count('-'))
    
    print(sum(dots), sum(hyphens))
    dots_sum.append(sum(dots))
    hyphens_sum.append(sum(hyphens))
    dots.clear()
    hyphens.clear()
    

    使用count 的代码,然后将列表中的点和连字符的总和附加到另外两个列表,然后清除仅保存每个网址的点数的两个列表。

    【讨论】:

      【解决方案3】:

      您可以使用collections.Counter 来简化此操作:

      from collections import Counter
      named_url = ['www.facebook.com', 'yahoo.com/index-true']
      for url in named_url:
          c = Counter(url)
          dots = c["."]
          dash = c["-"]
          print("{} contains: {} dot(s) and {} hyphen(s)".format(url, dots, dash))
      

      输出:

      www.facebook.com contains: 2 dot(s) and 0 hyphen(s)
      yahoo.com/index-true contains: 1 dot(s) and 1 hyphen(s)
      

      【讨论】:

        猜你喜欢
        • 2015-12-04
        • 2020-06-14
        • 2016-08-13
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-01-08
        • 1970-01-01
        相关资源
        最近更新 更多