【问题标题】:How can I fix this error for popping a word in a list/string? (Python 3.x)如何解决此错误以在列表/字符串中弹出单词? (Python 3.x)
【发布时间】:2021-08-07 15:18:38
【问题描述】:

我并不是那种你称之为“擅长”编码的人。在这种特殊情况下,在第 13 行,我试图弹出列表中的第一个单词,直到完成,但它一直给我“str”对象不能被解释为整数问题。

我在这里做错了什么?

n = n.split(" ")
N = n[0]
K = n[1]
f1 = input()
f1 = f1.split(" ")
f1 = list(f1)
current = 0
for x in f1:
    while current <= 7:
        print(x)
        f1 = list(f1.pop()[0])
        current = current + len(x)
        if current > 7:
            print("\n")
            current = 0

【问题讨论】:

  • 用你的变量命名,很难说你的代码到底应该做什么。你能解释一下你的目的吗?
  • 您能否分享一些示例输入和预期输出,然后解释错误会更容易...还有很好的提示 - 选择一些 meaningful 变量名。
  • @AKX 我正在练习 USACO 问题。这是链接:usaco.org/index.php?page=viewproblem2&cpid=987
  • @DanielHao 很抱歉我选择了变量名...我不知道给它们起什么名字,也许看看我的其他评论?
  • 您可能需要考虑 e. G。 “input_words”、“current_line_length”、“word”作为合适的变量名...

标签: python python-3.x string list python-3.8


【解决方案1】:

根据您的 cmets,此程序将拆分行以包含最多 K 个字符:

K = 7
s = "hello my name is Bessie and this is my essay"

out, cnt = [], 0
for word in s.split():
    l = len(word)
    if cnt + l <= K:
        cnt += l
        if not out:
            out.append([word])
        else:
            out[-1].append(word)
    else:
        cnt = l
        out.append([word])

print("\n".join(" ".join(line) for line in out))

打印:

hello my
name is
Bessie
and this
is my
essay

【讨论】:

    【解决方案2】:

    您可以尝试在索引上拆分字符串,然后在其中插入换行符。每次执行此操作时,您的字符串都会增加一个字符,因此我们可以使用 enumerate(从零开始计数)向切片索引添加一个数字。

    s = 'Thanks for helping me'
    
    new_line_index = [7,11, 19]
    
    for i, x in enumerate(new_line_index):
        s = s[:x+i] + '\n' + s[x+i:]
        
    print(s)
    

    输出

    Thanks 
    for 
    helping 
    me
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-09-15
      • 1970-01-01
      • 2021-12-23
      • 2019-04-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多