清单l具有以下元素

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


使用元组将列表l分成几对,这样每个字母对应于A:6,G:6,C:35等
如果值小于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控制台上工作是继续进行的最佳方法。因此,我将开始将不同的语句一一分开,然后看看每个语句的作用。现在,可能会有很多不同的方式来解释/重写该代码,因此我的方法将有望帮助您理解该过程。

您的代码不错,但是最终的所需输出存在一个问题和一个差异。


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


不过,您的工作非常出色。

最终的“新代码”如下所示,您可以在以下位置看到它的运行情况: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/

10-14 15:28
查看更多