python - 如何在嵌套的 for 和 if 循环中重写以下邮政编码?

标签 python if-statement for-loop

列表 l 具有以下元素

l = ['AGCTT 6 6 35 25 10', 'AGGGT 7 7 28 29 2']

列表 l 使用元组分成对,这样每个字母对应于 A:6、G:6、C:35 ..etc 如果值小于 10,则将字母转换为 Z。 代码如下:

pairs = []
for a, b in (sub.split(None, 1) for sub in l):
    pairs.append([("Z", i) if int(i) < 10 else (c, i) for c, i in zip(a,b.split())])
print(pairs)

如何使用嵌套的 for 和 if 循环编写相同的代码? (我需要做这个练习来帮助更好地理解 Python 编码)

这是我的尝试:

pairs =[]
for a, b in (sub.split(None, 1) #What is sub.split(None,1)
    for sub in l: 
        if int(i) < 10:
            pairs.append("Z",i)
        else:
            pairs.append(c,i)
print pairs

注 1:如果有人可以帮助我更好地针对具体问题提出问题,请提出更改建议

上述问题和代码(来源:P. Cunningham)可以在 here 找到

最佳答案

要对代码进行逆向工程,通常在 python 控制台上工作是最好的方法。因此,我将开始将不同的语句一一拆开,看看每个语句的作用。现在,可能会有许多不同的方法来解释/重写该代码,所以我的方法希望能够帮助您理解该过程。

您的代码很好,但有一个问题,并且与最终期望的输出有一个差异。

  1. 问题出在第一个循环:您应该将 for a, bfor sub in l 行交换,因为这会给您一个关于 sub 未定义等等。
  2. 差异在于 pairs 是列表的列表,而您正在尝试附加一个元组。我说“尝试”是因为该语句无效,应该写成 pairs.append(("Z",i)) 例如。但仍然错过了原始代码中定义的微妙的 list 。事实上,你有一个pairs.append([]),并且内部的完整逻辑创建了所谓的列表理解。

尽管如此,您的工作非常出色。

最终的“新代码”如下所示,您可以在以下位置查看它的实际效果:https://eval.in/639908

l = ['AGCTT 6 6 35 25 10', 'AGGGT 7 7 28 29 2']
pairs = []
# for each element in the list
for sub in l:   
    # we will create a new empty list
    new_list = []

    # split 'sub' into the string and the numbers parts
    a, b = sub.split(None, 1)   

    # further, split the numbers into a list
    numbers = b.split()

    # now using positional index, we will...
    for x in range(len(a)):
        # ... create a new tuple taking one character from string 
        # 'a' and one number from list 'numbers'
        new_tuple = ( a[x], numbers[x] )

        # if the value is less than 10, then...
        if int(numbers[x]) < 10:
            # ... let's just put "Z" 
            new_tuple = ("Z", numbers[x])   

        # append this to the temporary list
        new_list.append(new_tuple)    

    # once the sequence is complete, add it to the main list
    pairs.append(new_list)   

# When it's all done, print the list
print pairs

关于python - 如何在嵌套的 for 和 if 循环中重写以下邮政编码?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39442294/

相关文章:

python - python 中的振荡积分

python - 在 pandas df header 上添加描述符行

iphone - if 语句推送到 els 上的 viewController 不起作用

python - 如何从 Python 中为运行者指定输入文件?

python - 将 pandas Dataframe 转换为字典时保留行的顺序

if-statement - 二郎: nested cases

c# - 嵌套 'if' -'else' 语句

Python 从另一个列表创建特定列表

java - 如何在 java 的 for 循环中使用公式

java - 如何在方法中编写嵌套 for 循环(干净的代码)