【问题标题】:Python Loop and Append to StringPython循环并追加到字符串
【发布时间】:2020-08-09 19:26:52
【问题描述】:

我有一个字符串字段和一个数字数组。当我遍历列表时,我应该让字符串附加数组中的数字。

目前只返回字符串+数组的当前位置。以下是我的代码。我该如何解决这个问题?

digit_list = list(map(int, str(extra_digits)))
pi_local = "PI"
for digit in range(len(digit_list)):
    pi_local = pi_local + str(digit_list[counter])
    pi_label.config(text = pi_local)

initial incorrect output

我通过尝试遍历列表尝试了以下建议,但我仍然没有得到正确的结果。完整代码如下

pi = "PI"
extra_digits = "159265358979323846"


counter = 0
init = 2

#digit_list = list(map(int, str(extra_digits)))



def button_pressed():
    global counter
    global pi
    #global digit_list
    global init
    digit_list = list(map(int, str(extra_digits)))
    our_label.config(text="Pi to " + str(init+counter) + " decimals")
    pi_local = pi
    for digit in digit_list:
        pi_local = pi_local + str(digit)
        pi_label.config(text = str(digit))
        #pi_label.config(text = str(pi) + str(digit_list[counter]))
    counter = counter +  1

我得到的输出是Current incorrect output after using solution below

【问题讨论】:

  • 您能否通过给定的输入输出示例阐明您的预期
  • 什么是ˋcounterˋ?你知道你可以直接迭代一个列表,而不用索引吗?当您只需要一个字符串时,为什么要将输入转换为整数列表?
  • 您的预期输出是什么?另外,请将您观察到的输出添加为文本而不是图片。

标签: python string loops


【解决方案1】:
In [77]: pi_local = "PI"                                                                                                                                                                                    

In [78]: digit_list = [1,3,5,2]                                                                                                                                                                             

In [79]: [str(i) + pi_local for i in digit_list]                                                                                                                                                            
Out[79]: ['1PI', '3PI', '5PI', '2PI']

【讨论】:

    【解决方案2】:

    你需要遍历digit_list中的元素

    digit_list = list(map(int, str(extra_digits)))
    pi_local = "PI"
    for digit in digit_list:
        pi_local = pi_local + str(digit)
        pi_label.config(text = pi_local)
    

    【讨论】:

    • 嗨,我的源数据如下extra_digits = "159265358979323846" ,我也使用digit_list = list(map(int, str(extra_digits)))将其转换为列表地图
    • 我的要求是每次我点击 Next Digit 按钮时,它都会将特定计数器上的数字附加到我正在打印的字符串中。
    猜你喜欢
    • 2020-06-29
    • 2011-12-24
    • 1970-01-01
    • 2019-02-08
    • 1970-01-01
    • 2015-07-31
    • 2019-02-03
    • 1970-01-01
    • 2014-05-08
    相关资源
    最近更新 更多