Python while循环返回第N个字母

huangapple go评论92阅读模式
英文:

Python while loop return Nth letter

问题

X = ['kmo', 'catlin', 'mept']

result = []
max_length = max(len(word) for word in X)

for i in range(max_length):
    nth_letters = [word[i] if i < len(word) else '' for word in X]
    result.append(nth_letters)

result

这是一个根据你提供的问题编写的代码示例。它会生成一个包含每个单词第N个字母的列表嵌套列表。在给定的例子中,它将返回[['k', 'c', 'm'], ['m', 'a', 'e'], ['o', 't', 'p']]

英文:

I have a list of strings

X=[&#39;kmo&#39;,&#39;catlin&#39;,&#39;mept&#39;]

I was trying to write a loop that would return a list that contains lists of every Nth letter of each word:

[[&#39;k&#39;,&#39;c&#39;,&#39;m&#39;], [&#39;m&#39;,&#39;a&#39;,&#39;e&#39;],[&#39;o&#39;,&#39;t&#39;,&#39;p&#39;]]

But all the methods I tried only returned a list of all the letters returned consecutively in one list:

[&#39;k&#39;,&#39;m&#39;,&#39;o&#39;,&#39;c&#39;,&#39;a&#39;,&#39;t&#39;,&#39;l&#39;,&#39;i&#39;.....&#39;t&#39;] 

Here is one version of my code:

def letters(X):
    prefix=[]
    for i in X:
      j=0
      while j &lt; len(i):
        while j &lt; len(i):
          prefix.append(i[j])
          break
        j+=1
    return prefix

I know I'm looping within each word, but I'm not sure how to correct it.

答案1

得分: 7

以下是代码部分的翻译:

It seems that the length of the resulting list is dictated by the length of the smallest string in the original list. If that is indeed the case, you could simply do it like this:

    X = ['kmo','catlin','mept']

    l = len(min(X, key=len))

    res = [[x[i] for x in X] for i in range(l)]

which returns:

    print(res)  # -> [['k', 'c', 'm'], ['m', 'a', 'e'], ['o', 't', 'p']]

or the even simpler (kudos @JonClemens):

    res = [list(el) for el in zip(*X)]

with the same result. Note that this works because `zip` automatically stops iterating as soon as one of its elements is depleted.

If you want to *fill the blanks* so to speak, `itertools` has got your back with its `zip_longest` method. See [this](https://docs.python.org/3.8/library/itertools.html#itertools.zip_longest) for more information. The `fillvalue` can be anything you chose; here, '-' is used to demonstrate the use. An empty string '' might be a better option for *production code*.

    res = list(zip_longest(*X, fillvalue = '-'))
    print(res)  # -> [('k', 'c', 'm'), ('m', 'a', 'e'), ('o', 't', 'p'), ('-', 'l', 't'), ('-', 'i', '-'), ('-', 'n', '-')]

请注意,以上内容是代码的翻译部分,没有包括问题的回答。

英文:

It seems that the length of the resulting list is dictated by the length of the smallest string in the original list. If that is indeed the case, you could simply do it like this:

X = [&#39;kmo&#39;,&#39;catlin&#39;,&#39;mept&#39;]

l = len(min(X, key=len))

res = [[x[i] for x in X] for i in range(l)]

which returns:

print(res)  # -&gt; [[&#39;k&#39;, &#39;c&#39;, &#39;m&#39;], [&#39;m&#39;, &#39;a&#39;, &#39;e&#39;], [&#39;o&#39;, &#39;t&#39;, &#39;p&#39;]]

or the even simpler (kudos @JonClemens):

res = [list(el) for el in zip(*X)]

with the same result. Note that this works because zip automatically stops iterating as soon as one of its elements is depleted.


If you want to fill the blanks so to speak, itertools has got your back with its zip_longest method. See this for more information. The fillvalue can be anything you chose; here, &#39;-&#39; is used to demonstrate the use. An empty string &#39;&#39; might be a better option for production code.

res = list(zip_longest(*X, fillvalue = &#39;-&#39;))
print(res)  # -&gt; [(&#39;k&#39;, &#39;c&#39;, &#39;m&#39;), (&#39;m&#39;, &#39;a&#39;, &#39;e&#39;), (&#39;o&#39;, &#39;t&#39;, &#39;p&#39;), (&#39;-&#39;, &#39;l&#39;, &#39;t&#39;), (&#39;-&#39;, &#39;i&#39;, &#39;-&#39;), (&#39;-&#39;, &#39;n&#39;, &#39;-&#39;)]

答案2

得分: 3

You can use zip.

output=list(zip(*X))
print(output)

*X会解包X中的所有元素。

解包后,我将它们一起使用zip()函数组合在一起。zip()函数返回一个zip对象,它是一个由元组组成的迭代器,其中每个传递的迭代器的第一个项目配对在一起,然后每个传递的迭代器的第二个项目等等。最后,我使用list将所有内容封装在一个列表中。


output

[('k', 'c', 'm'), ('m', 'a', 'e'), ('o', 't', 'p')]


如果你想要output是一个列表的列表。那么可以使用map

output=list(map(list,zip(*X)))
print(output)


output

[['k', 'c', 'm'], ['m', 'a', 'e'], ['o', 't', 'p']]

英文:

You can use zip.

output=list(zip(*X))
print(output)

*X will unpack all the elements present in X.

After unpacking I'm zipping all of them together. The zip() function returns a zip object, which is an iterator of tuples where the first item in each passed iterator is paired together, and then the second item in each passed iterator are paired together etc. Finally, I wrapped everything in a list using list.


output

[(&#39;k&#39;, &#39;c&#39;, &#39;m&#39;), (&#39;m&#39;, &#39;a&#39;, &#39;e&#39;), (&#39;o&#39;, &#39;t&#39;, &#39;p&#39;)]

If you want output to be a list of lists. Then use map.

output=list(map(list,zip(*X)))
print(output)

output

[[&#39;k&#39;, &#39;c&#39;, &#39;m&#39;], [&#39;m&#39;, &#39;a&#39;, &#39;e&#39;], [&#39;o&#39;, &#39;t&#39;, &#39;p&#39;]]

答案3

得分: -1

X = ['kmo', 'catlin', 'mept']
y = []
j = 0

for i in X:
    item = ''
    for element in X:
        if (len(element) > j):
            item = item + element[j]

    y.append(item)
    j = j + 1

print("X = [", X, "]")
print("Y = [", y, "]")

[![result][1]][1]

这是您提供的代码的中文翻译部分。

<details>
<summary>英文:</summary>

&gt;     X=[&#39;kmo&#39;,&#39;catlin&#39;,&#39;mept&#39;]
&gt;     y = []
&gt;     j=0
&gt;     
&gt;     for i in X:
&gt;         item =&#39;&#39;
&gt;         for element in X :
&gt;             
&gt;             if (len(element) &gt; j):
&gt;                 item = item + element[j]
&gt;             
&gt;             
&gt;         y.append(item)
&gt;         j=j+1
&gt;     print(&quot;X = [&quot;,X,&quot;]&quot;)
&gt;     print(&quot;Y = [&quot;,y,&quot;]&quot;)

[![result][1]][1]


  [1]: https://i.stack.imgur.com/osWrV.png

</details>



# 答案4
**得分**: -3

尝试这个

```python
def letters(X):
    prefix=[]
    # 首先让我们将列表元素进行zip操作
    zip_elemets =  zip(*X)

    for element in zip_elemets:
        prefix.append(list(element))
    
    return prefix
英文:

try this

def letters(X):
    prefix=[]
    # First lets zip the list element
    zip_elemets =  zip(*X)

    for element in zip_elemets:
        prefix.append(list(element))
    
    return prefix

huangapple
  • 本文由 发表于 2020年1月6日 22:27:18
  • 转载请务必保留本文链接:https://go.coder-hub.com/59613810.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定