python 列表中唯一出现的期间

hm2xizp9  于 2023-01-29  发布在  Python
关注(0)|答案(2)|浏览(88)

我使用textrap模块将字符串拆分为一个宽度为40的列表。然后,我尝试迭代该列表,每隔一个周期,输入“We hit second period”,然后重置计数。我认为我遇到的问题是,如果列表中有多个周期,我的迭代就不起作用。运行以下代码后,我得到两次“We hit second period”。而不是3次,因为列表中有6个时段。

import textwrap
text = "We are having a long, long long very long sentence here. Just trying to test if it works. We are trying to test. Testing we do. All day. Long."
unique_character = textwrap.wrap(text, width=40)
x=0
for items in unique_character:
    print(items)
    items.count(".")
    if x == 0:
        x+=1
    elif x==1:
        x+=1
    elif x ==2:
        print("We hit second period")
    else:
        x=0
eoxn13cs

eoxn13cs1#

您没有使用值items.count(".") returnes。我还创建了一个解决方案,该解决方案不使用它,因为如果我们一次添加3个或更多,则在一行中添加.的数量将不起作用。

import textwrap
text = "We are having a long, long long very long sentence here. Just trying to test if it works. We are trying to test. Testing we do. All day. Long."
unique_character = textwrap.wrap(text, width=40)
period_count = 0
for items in unique_character:
    print(items)
    for l in items:
        if l == ".":
            period_count += 1
            if period_count % 2 == 0 and period_count:
                print("We hit second period")
kpbwa7wx

kpbwa7wx2#

实际上,需要将items.count的结果保存到一个变量中,并将其添加到累加器中。

import textwrap
text = "We are having a long, long long very long sentence here. Just trying to test if it works. We are trying to test. Testing we do. All day. Long."
unique_character = textwrap.wrap(text, width=40)
accumDots = 0
for line in unique_character:
    print(line)
    dots = line.count(".")
    if accumDots + dots >= 2:
        print("We hit second period")
        accumDots = 0
    else:
        accumDots += dots

相关问题