【问题标题】:creating list from a string and than change that new list从字符串创建列表,然后更改该新列表
【发布时间】:2022-11-17 09:49:20
【问题描述】:

大家好,这是我第一次来这里。我是初学者,我想检查如何从给定的字符串中获取 (即:string="5,93,14,2,33")创建一个列表,然后从列表中获取每个数字的平方,然后将该列表(带有平方值)返回到字符串中?

输入应该是: 字符串 = "5,93,14,2,33"

输出: 字符串 = "25,8649,196,4,1089"

我试图用 .split() 制作新列表,而不是对每个元素进行平方,但我知道我没有用 int() 转换字符串。我只是不能把所有这些放在一起,所以我希望你们能帮忙。谢谢,对不起,如果这个问题很愚蠢,我才刚刚开始学习

【问题讨论】:

  • 请显示您正在使用的代码以及您到目前为止所做的努力。

标签: python string list


【解决方案1】:

是的,你开始正确。

# First, let's split into a list:
list_of_str = your_list.split(',') # '2,3,3,4,5' -> ['2','3','4','5']

# Then, with list comprehension, we transform each string into integer 
# (assuming there will only be integers)
list_of_numbers = [int(number) for number in list_of_str]

现在你有了整数列表!

【讨论】:

    猜你喜欢
    • 2020-04-21
    • 1970-01-01
    • 2011-04-20
    • 1970-01-01
    • 2014-02-10
    • 2016-02-13
    • 2021-01-29
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多