【问题标题】:How can I add two or more elements to a list from a single input in Python?如何从 Python 中的单个输入将两个或多个元素添加到列表中?
【发布时间】:2020-11-15 03:40:43
【问题描述】:

我的脚本现在正在做的是将元素添加到列表中。例如,如果用户键入“JO”,我会将“John”添加到列表中。我现在要做的是,如果用户键入“2 JO”,我将两个元素添加到列表中:“John”和“John”。 这是数据库现在的样子:

Sample database copy.png

这是现在的代码:

import pandas
data = pandas.read_excel("Sample database copy.xlsx")
name = dict(zip(data["Abbreviation"],data["Name"]))
list1 = []
incoming_msg = input(Please type what you want to add: )
list1.append(name[incoming_msg])

我需要从同一个输入中完成所有操作,我不能单独询问数量和缩写。我想知道是否有任何库可以轻松地做到这一点,因为我是初学者。如果没有库,但您知道我该如何解决它,那也很棒。

非常感谢您!

【问题讨论】:

  • 用于查找模式和解析字符串的模块是 re(正则表达式)。在这种情况下,您不需要正则表达式,因为模式很简单,但对于更复杂的模式,正则表达式是一个很好的工具,可以让您的生活更轻松。
  • 首先,感谢您花时间回答。你有任何关于我如何使用它的例子吗?几周前我开始编码,我读的都是中文????

标签: python python-3.x pandas list


【解决方案1】:

您可以使用 string.split() 将字符串按空格拆分为一个列表,然后使用第一个元素乘以包含字典中的值的列表并将其递增到结果列表。看代码

name = dict(zip(data["Abbreviation"],data["Name"]))
list1 = []
incoming_msg = input('Please type what you want to add: ')
incoming_msg = incoming_msg.split() # split the string by space
if len(incoming_msg) == 2: # if there are two elements in the list (number and name)
    list1 += [name[incoming_msg[1]]] * int(incoming_msg[0])
else:
    list1.append(name[incoming_msg[0]])

【讨论】:

  • 除了删除对象外,我怎么能做同样的事情?我正在尝试使用运算符 -= 但它不起作用。
猜你喜欢
  • 1970-01-01
  • 2021-02-27
  • 1970-01-01
  • 2015-03-07
  • 2021-07-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多