简体   繁体   English

如何将for循环的每次迭代的结果存储在变量中

[英]How do I store the results of each iteration of a for loop inside a variable

I wrote the following code:我写了以下代码:

full_name = "John Francis Bean Coppola"
full_name_as_list = full_name.lower().split()

for name in (full_name_as_list):
a = name[0]
print(a)

When I run print(a) It returns:当我运行 print(a) 它返回:

j
f
b
c

I wanna define a variable like joined_results = something such that if I run print(joined_results) it returns:我想定义一个像joined_results =这样的变量,如果我运行 print(joined_results) 它会返回:

jfbc

The purpose of the code I'm trying to write is to extract the initials of a name to create an e-mail address.我尝试编写的代码的目的是提取姓名的首字母以创建电子邮件地址。 For example: John Francis Ford Coppola = jffc@gmail.com例如:约翰·弗朗西斯·福特·科波拉 = jffc@gmail.com

full_name = "John Francis Bean Coppola"
full_name_as_list = full_name.lower().split()

initials = []
for name in (full_name_as_list):
    initials.append(name[0])

#edit
print(''.join(initials))

You can use join to join together all the items in a list.您可以使用join将列表中的所有项目连接在一起。

print("".join([name[0] for name in full_name_as_list]))

Here, I'm joining the items together with a blank string, but for other applications, you can join them with anything, like so:在这里,我将这些项目与一个空白字符串连接在一起,但对于其他应用程序,您可以将它们与任何东西连接起来,如下所示:

print("&".join([name[0] for name in full_name_as_list]))

would print会打印

j&f&b&c

暂无
暂无

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

相关问题 如何将 for 循环的每次迭代的结果存储在 dataframe 中 - How to store the results of each iteration of for loop in a dataframe 如何存储从for循环收集的信息并通过count迭代将其分配给变量? - How do I store information collected from a for loop and assign it to a variable with the count iteration? 如何在Python 3中为每个for循环迭代将step变量加倍? - How do I double my step variable for each for-loop iteration in Python 3? 如何在 Python 中打印出 for 循环的每次迭代? - How do I print out each iteration of the for loop in Python? 如何在列表理解中的每次迭代中更改变量? - How do I change a variable in each iteration in a list comprehension? 我可以将来自 for 循环的数据存储为每次迭代的不同变量吗? - Can I store data from a for-loop as a different variable for each iteration? 用python语言编码时,如何将每次迭代产生的值存储在FOR循环中? - How can i store the value produced by each iteration in a FOR loop when coding in python language? 如何在for循环中迭代项目,然后将for循环迭代结果打印到文本文件中? - How do I iterate items in a for loop and then print the for loop iteration results into textfile? 如何将for循环的每次迭代结果存储到python中的数组中 - how to store the result of each iteration of for loop into an array in python 如何使内循环考虑外循环的每次迭代? - How do I make the inner loop consider each iteration of the outer loop?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM