【问题标题】:Perl to Python script hashingPerl 到 Python 脚本散列
【发布时间】:2019-01-14 09:42:20
【问题描述】:
if ( ! exists $tRHash{$tR} ) {

    if ( $start < $end ) {

        $pS = $start - 41;
        $pE = $end + 40;
        print "$chr\t$pS\t$pE\tpre-$tR\t0\t$st\n";
    }
    else {

        $pS = $end - 40;
        $pE = $start + 40;
        print "$chr\t$pS\t$pE\tpre-$tR\t0\t$st\n";
    }

    $tRHash{$tR} = $tR;
}

如何在 Python 中做到这一点,尤其是哈希部分?我已经执行了if 语句,但我正在努力处理 Perl 中的输出格式。

pS, pE = zip(*[(n - 41, m + 40) if n < m else (n + 40, m - 40)
           for n, m in zip(start, end)])

【问题讨论】:

  • 您展示的 Python 与 Perl 代码的工作方式不同。当 Perl 中的简单 if else 就足够时,为什么还要使用花哨的列表解析?

标签: python-2.7 perl hash


【解决方案1】:

如果您只需要 print 语句,那么这应该会有所帮助

我不知道你的变量包含什么样的数据,所以我假设chr 是一个字符的字符串,其他都是整数

chr = 'A'
pS = 100
pE = 208
tR = 10
st = 20

print "%s\t%d\t%d\tpre-%d\t0\t%d\n" % (chr, pS, pE, tR, st);

输出

A   100 208 pre-10  0   20

【讨论】:

  • 如果数据是像 Abc-47-1 这样的字母数字应该使用什么占位符
  • @KR12:这是一串字符,所以使用%s
【解决方案2】:

我也找了很久,现在我完成了Python培训,这是我的理解。

请在python中使用字典 数据类型,它非常类似于 hash...它还支持嵌套,类似于嵌套哈希。

唯一的一点是您需要在 python 中搜索 Dictionary 而不是在 Perl 中搜索 Hash

希望这个例子能帮助你理解:-

dict = {'Name': 'Zara', 'Age': 7, 'Class': 'First'}
dict['Age'] = 8; # update existing entry
dict['School'] = "DPS School" # Add new entry

print ("dict['Age']: ", dict['Age'])
print ("dict['School']: ", dict['School'])

字典数据类型:- https://www.tutorialspoint.com/python3/python_dictionary.htm

希望它能解决问题..

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-03-13
    • 2013-03-14
    • 2019-01-13
    • 1970-01-01
    • 1970-01-01
    • 2012-02-20
    • 2013-02-24
    • 2012-08-03
    相关资源
    最近更新 更多