【问题标题】:How to print multiple values from for loop inside print statement in a single line?如何在一行打印语句中的 for 循环中的多个值?
【发布时间】:2020-06-09 02:58:14
【问题描述】:

我的代码有类似的东西:

user = input("Enter username: ")

我有 10 个变量,例如:

ch1 = "String1"
ch2 = "String2"
ch3 = "String3"
ch4 = "String4"
...

假设输入的用户名是 Pawan,我的输入语句返回一个列表:

basic_choices = input("Enter All your choices separated by ',' to perform in your remote system together: ").strip().split(',')

输出是列表中从 1 到 10 的一些随机数:

['1','3','7']

现在我想根据用户的选择在一行中打印一个字符串:

对于 1,3,7 应该给出输出:

The strings selected by you are String1; String3; String7; in the strings list of Pawan

(应包含分号) 我尝试了很多方法,但它不起作用,要么只返回第一个数字的值,要么返回地址处的生成器对象

print("The strings selected by you are ch{0}; in the strings list of {1}".format(*basic_choices, user))
print("The strings selected by you are ch{0}; in the strings list of {1}".format(choice, user) for choice in basic choices)</p>

【问题讨论】:

  • 您应该考虑将输入字符串(如 "1")转换为整数,然后使用它来索引您的列表(例如 1 -> items[0] -> "String1")。您需要将ch1, ch2, ... 放入列表中以执行此操作

标签: python python-3.x list for-loop


【解决方案1】:

我认为将“字符串”放入字典中是有意义的,其中键是可能的用户输入。然后我使用str.join 正确格式化输出:

user = 'Pawan'

ch1 = "String1"
ch2 = "String2"
ch3 = "String3"
ch4 = "String4"
ch5 = "String5"
str_options = {'1':ch1,'2':ch2,'3':ch3,'4':ch4,'5':ch5}

basic_choices = input("Enter All your choices separated by ',' to perform in your remote system together: ").strip().split(',')

chosen = [str_options[i] for i in basic_choices]

print("The strings selected by you are " + 
      "; ".join(chosen) + 
      "; in the strings list of {}".format(user))

请注意,如果用户输入不在字典中,这将引发错误。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-07-31
    • 2021-12-24
    • 2020-06-18
    • 1970-01-01
    • 1970-01-01
    • 2021-09-27
    • 2021-03-25
    相关资源
    最近更新 更多