【问题标题】:List, str and int help in pythonpython中的list、str和int帮助
【发布时间】:2012-07-06 17:57:31
【问题描述】:

我有这样的号码列表:

146、168

174、196

230, 252

258、280

286、308

314, 336

342、364

370, 392

第一个数字代表我从代码中得到的值(起始数字),逗号后面的第二个数字是结束值。我尝试做的是同时使用开始值和结束值来打印字符串。 这是我的代码的一部分:

root = etree.parse(f)

for lcn in root.xpath("/protein/match[@dbname='DB']/lcn"):
    start = lcn.get("start")
    end = lcn.get("end")
    print "%s, %s" % (start, end,)
    if start <= end:
        start = int(start+1)
        print start    
    if start <= end:

      print list(start)

      start = int(start+1)

我收到错误消息说我无法连接“str”和“int”对象。旁注:在列表索引中有一个字母。所以我的目标是在每个开始值和结束值的一行上打印出这些字母。例如 ACTGAGCAG 并可能导入到另一个输出文件。你能帮我解决这个问题吗?

更新:一切顺利,我得到了结果,但现在我想让它们出现在一行上。我这样做了,但我收到错误消息说 TypeError: 'builtin_function_or_method' object is not subscriptable

    while start <= end:
        inRange = makeList.append[start]
        start += 1
        print inRange

【问题讨论】:

    标签: python elementtree


    【解决方案1】:

    代替

    start = lcn.get("start")
    end = lcn.get("end")
    

    使用

    start = int(lcn.get("start"))
    end = int(lcn.get("end"))
    

    这是因为lcn.get 返回一个字符串。

    使用start += 1 代替start = int(start+1)。您不再需要转换为整数,start += 1 是 start = start + 1 的简写。

    使用print "%d, %d" % (start, end) 代替print "%s, %s" % (start, end,)。最后的逗号是不必要的,start 和 end 现在是整数,所以使用 %d 而不是 %s。

    更新:

    而不是

    while start <= end:
        inRange = makeList.append[start]
        start += 1
        print inRange
    

    使用

    for i in range(start, end):
        makeList.append(i)
        print(i)
    

    如果使用 Python 3 或使用

    for i in xrange(start, end):
        makeList.append(i)
        print i
    

    如果使用 Python 2。

    【讨论】:

    • @ChadD,没问题。一旦你被允许,请务必接受这个答案。 :)
    • 我刚做了。再次感谢。所以我开始工作了,但结果是每行一个字母,我这样做了.. while start
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-26
    • 1970-01-01
    • 2014-10-15
    • 2023-03-25
    相关资源
    最近更新 更多