英文:
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=['kmo','catlin','mept']
I was trying to write a loop that would return a list that contains lists of every Nth letter of each word:
[['k','c','m'], ['m','a','e'],['o','t','p']]
But all the methods I tried only returned a list of all the letters returned consecutively in one list:
['k','m','o','c','a','t','l','i'.....'t']
Here is one version of my code:
def letters(X):
prefix=[]
for i in X:
j=0
while j < len(i):
while j < 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 = ['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 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', '-')]
答案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
[('k', 'c', 'm'), ('m', 'a', 'e'), ('o', 't', 'p')]
If you want output
to be a list of lists. Then use map
.
output=list(map(list,zip(*X)))
print(output)
output
[['k', 'c', 'm'], ['m', 'a', 'e'], ['o', 't', 'p']]
答案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>
> 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]
[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
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论