简体   繁体   English

如何修改列表元素?

[英]How to modify list element?

I have two python lists:我有两个 python 列表:

name = ['Beijing']
alphabet = ['a', 'b', 'c']

I need to add each element of alphabet to the element in name such that output is :我需要将字母表的每个元素添加到 name 中的元素,以便输出:

new_name = ['Beijinga', 'Beijingb', 'Beijingc']

Can someone please help me with this?有人可以帮我解决这个问题吗?

You can use string concatenation with list comprehension:您可以将字符串连接与列表理解一起使用:

name = ['Beijing']
alphabet = ['a', 'b', 'c']
new_name=[name[0]+x for x in alphabet]
print(new_name)

If there are multiple elements:如果有多个元素:

name = ['Beijing']
alphabet = ['a', 'b', 'c']
new_name=[names+x for names in name for x in alphabet]
print(new_name)
name = ['Beijing'] alphabet = ['a', 'b', 'c'] new_name = [name[0]+i for i in alphabet]

You can try in the following example.您可以在以下示例中尝试。

import string
name = 'Beijing'
new_nam = [name + item for item in string.ascii_lowercase]

Output:输出:

['Beijinga', 'Beijingb', 'Beijingc', 'Beijingd', 'Beijinge', 'Beijingf', 'Beijingg', 'Beijingh', 'Beijingi', 'Beijingj', 'Beijingk', 'Beijingl', 'Beijingm', 'Beijingn', 'Beijingo', 'Beijingp', 'Beijingq', 'Beijingr', 'Beijings', 'Beijingt', 'Beijingu', 'Beijingv', 'Beijingw', 'Beijingx', 'Beijingy', 'Beijingz']

If you are a beginner at Python this code may help you.如果您是 Python 的初学者,此代码可能对您有所帮助。

names = ['Beijing']
alphabet = ['a', 'b', 'c']

newName = []

for name in names:
    for letter in alphabet:
        newName.append(f"{name}{letter}")

In your example, you have only one name .在您的示例中,您只有一个 name Assuming you will have many names , I have a solution (It would work for single names too) -假设你有很多名字,我有一个解决方案(它也适用于单个名字)-

name = ['Beijing','QWERTY']
alphabet = ['a', 'b', 'c']

new_lst = []
for j in name:
    for i in alphabet:
        new_lst.append(j+i)

Result :结果

['Beijinga', 'Beijingb', 'Beijingc', 'QWERTYa', 'QWERTYb', 'QWERTYc']

Or, you could use a list comprehension which is better and makes it easier -或者,您可以使用更好且更容易的列表理解-

new_lst = [j+i for j in name for i in alphabet]
print(new_lst)

If you have two lists of arbitrary size, you can use itertools.product() to do this quite easily:如果你有两个任意大小的列表,你可以使用itertools.product()很容易地做到这一点:

>>> import itertools
>>> name = ['Beijing']
>>> alphabet = ['a', 'b', 'c']
>>> new_name = list(map(''.join, itertools.product(name, alphabet)))
>>> new_name
['Beijinga', 'Beijingb', 'Beijingc']

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM