2012-09-23 114 views
1

是否有任何方式在Python中的列表中的元素不会被更改。Python列表输入 - 整数和字符串

对于例如,整数必须保持整数,字符串必须保持字符串,但这应该在同一个程序中完成。

示例代码将是:

print("Enter the size of the list:") 
N = int(input()) 
for x in range(N): 
    x = input("")  
    the_list.append(x) 
    the_list.sort() 

print(the_list) 

结果:the_list = ['1','2','3']

是把整数已转换为字符串这是错误的整数列表。

但是,列表中的字符串必须保持字符串。

+0

“正在生成”? - 什么是生成列表?没有什么能自动将整数转换为字符串。恐怕我不明白你的问题。你可以发布一些示例代码,并指出它不是在做你想做的事情吗? –

+0

@vamosrafa ..它不能自动转换,除非你明确地给字符串形式的整数。 –

+0

你的编辑没有更清晰。请显示生成'mylist_int'的代码。 –

回答

2
for x in range(N): 
    x = input("") 
    try: 
     the_list.append(int(x)) 
    except ValueError: 
     the_list.append(x) 

让我们来运行这个命令:

1 
hello 
4.5 
3 
boo 
>>> the_list 
[1, 'hello', '4.5', 3, 'boo'] 

请注意,您无法排序以有意义的方式列表(Python的2)或全部(Python 3中),如果它包含混合类型:

>>> sorted([1, "2", 3])      # Python 3 
Traceback (most recent call last): 
    File "<stdin>", line 1, in <module> 
TypeError: unorderable types: str() < int() 

>>> sorted([1, "2", 3])      # Python 2 
[1, 3, '2']