How can i zip() two lists together without the output having "\n" at the beginning of every second element?

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

How can i zip() two lists together without the output having "\n" at the beginning of every second element?

问题

I currently have two lists

songlist = []
artistlist = []

I return

list(zip(songlist, artistlist))

and it gives me what I want (a 3d list of a 2d list containing each song title and respective artist) but before each second item in each list is "\n."

For example, a list in the 3d list would look like: ["Amarillo By Morning", "\nGeorge Strait"]

I'm gonna be using the artist in a later function, so I'd rather there not be the "\n" there.

Instead of my above code, I tried returning a variable containing:

[i + j for i, j in zip(songlist, artistlist)]

but that just returned: ["Amarillo By Morning\nGeorge Strait", ... cont`.

英文:

I currently have two lists

songlist = []
artistlist = []

I return

list(zip(songlist, artistlist))

and it gives me what I want(a 3d list of a 2d list containing each song title and respective artist) but before each second item in each list is "\n"

for example a list in the 3d list would look like: ["Amarillo By Morning","\nGeorge Strait"]

I'm gonna be using the artist in a later function so I'd rather there not be the \n there.

instead of my above code i tried returning a variable containing:

[i + j for i, j in zip(songlist, artistlist)]

but that just returned: ["Amarillo By Morning\nGeorge Strait", ... cont.

答案1

得分: 1

你可以在每次遇到 artist 时对其进行修改,而不必创建另一个迭代器,如果无法在源头修改它。

如果你想要一个列表,而不是使用字符串连接,也可以返回一个列表。

[[song, artist.strip()] for song, artist in zip(songlist, artistlist)]
英文:

To avoid making another iterator, you can just modify each artist as they come along, if you can't modify it at the source.

Also, return a list instead of using string concatenation if you want a list.

[[song, artist.strip()] for song, artist in zip(songlist, artistlist)]

huangapple
  • 本文由 发表于 2023年2月7日 05:05:09
  • 转载请务必保留本文链接:https://go.coder-hub.com/75366572.html
匿名

发表评论

匿名网友

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

确定