【问题标题】:how to separate a mixed datatype string taken as input into list如何将作为输入的混合数据类型字符串分隔到列表中
【发布时间】:2017-10-04 23:52:52
【问题描述】:

考虑下面的代码,

string_new=raw_input('Enter data')

提供的输入是:

'aaa' 'bbb' 23 21 56 98 'ccc'

上述每个值都是用空格分隔的

我们要求将其转换为列表:

list=['aaa','bbb',23,21,56,98,'ccc']

我尝试了之前给出的解决方案 Get a list of numbers as input from the user

和 How to make a list from a raw_input in python?

使用

map(int,string_new.split())

但这仅适用于整数,我们有不同的数据类型元素作为输入传递并用空格分隔。

任何建议...

【问题讨论】:

  • 我们的字符串带有混合数据类型 不是真的 - 字符串就是字符串,即使它包含数字。

标签: python list


【解决方案1】:

原始输入将用户的输入转换为字符串。以下将根据您的要求生成一个按空格拆分的列表。

string_new = raw_input('Enter data')
input_list = string_new.split()

如果您希望在 input_list 中转换整数样:

mix_list = []
for in_string in input_list:
    try:
        mix_list.append(int(in_string))
    except:
        mix_list.append(in_string)

【讨论】:

  • @FarhanPatel raw_input 给你一个字符串,split() 只对字符串起作用。
  • @patrick,但这不是我们想要的输出!!!.... split 会导致 [' "aaa" ', ' "bbb" ', '23','21' .....
  • @BryceFrank,嘿,伙计,请在任何 python ide 中运行编辑后的答案,你会看到如果它不是整数,它会导致 [' "aaa" ', ' "bbb" '] .....在它变成字符串的地方.....
  • 另外,我建议对 string_new 和 string_input 变量不匹配进行编辑!!!...@BryceFrank 请验证!!
猜你喜欢
  • 1970-01-01
  • 2011-03-18
  • 1970-01-01
  • 2014-04-02
  • 2017-04-28
  • 1970-01-01
  • 2021-02-26
  • 2010-10-19
  • 2020-01-22
相关资源
最近更新 更多