私は「[[タイプを変更つまり、int型全リストのPythonの変更タイプ?
の完全なリストにSTRの完全なリスト、すなわち、ネストされたリストのためにそれを行うための簡単な方法をこの
def foo(x,dtype=long):
return magic_function_changing_listtype_to_dtype(x)
ような何かをしたいと思います1 ']、[' 2' ] - > INT
私は「[[タイプを変更つまり、int型全リストのPythonの変更タイプ?
の完全なリストにSTRの完全なリスト、すなわち、ネストされたリストのためにそれを行うための簡単な方法をこの
def foo(x,dtype=long):
return magic_function_changing_listtype_to_dtype(x)
ような何かをしたいと思います1 ']、[' 2' ] - > INT
str_list = ['1', '2', '3']
int_list = map(int, str_list)
print int_list # [1, 2, 3]
任意に深くネストされたリストのための点の
def intify(iterable):
result = []
for item in iterable:
if isinstance(item, list):
result.append(intify(item))
else:
result.append(int(item))
return result
作品:
>>> l = ["1", "3", ["3", "4", ["5"], "5"],"6"]
>>> intify(l)
[1, 3, [3, 4, [5], 5], 6]
リストの内包表記は、それを行う必要があります。
a = ['1','2','3']
print [int(s) for s in a] # [1, 2, 3]]
ネストされた:
ここa = [['1', '2'],['3','4','5']]
print [[int(s) for s in sublist] for sublist in a] # [[1, 2], [3, 4, 5]]
これは私が欲しいものではありません。intからあなたが望む他のdtypeに変更することができないからです。 – bios
@bios:これを一般化する関数を書く方法を知っています。 –
@biosはい、できます。 intを変数に置き換えます。その変数は、あなたが望む型です。 –
がためにかなり単純な再帰関数であります任意の深さのネストされたリストを変換する:
def nested_change(item, func):
if isinstance(item, list):
return [nested_change(x, func) for x in item]
return func(item)
>>> nested_change([['1'], ['2']], int)
[[1], [2]]
>>> nested_change([['1'], ['2', ['3', '4']]], int)
[[1], [2, [3, 4]]]
a=input()#taking input as string. Like this-10 5 7 1(in one line)
a=a.split()#now splitting at the white space and it becomes ['10','5','7','1']
#split returns a list
for i in range(len(a)):
a[i]=int(a[i]) #now converting each item of the list from string type
print(a) # to int type and finally print list a
このコードにいくつかの説明を加えてください。 –
あなたは、リストを変異させるか、新しいものを取得したいですか? –