![](/img/trans.png)
[英]How to make List in python dataclass that can accept multiple different types?
[英]How to make multiple changes to contents in a list with regard to their types?
說我有一個列表['GBP', 31, 'PIT', 25, ['Football]]
但我想對其進行修改,以便所有整數都比原始整數少7,並且所有列表都轉換為字符串'Football'
。 我不太確定如何讓python掃描列表中的每個項目,確定其類型,並進行相應的更改。 我嘗試了類似的東西
for x in the_list:
if type(x) == ......:
x = .....
但這確實不起作用...
使用isinstance()
:
the_list = ['GBP', 31, 'PIT', 25, ['Football']]
for i, x in enumerate(the_list):
if isinstance(x, list):
the_list[i] = 'Football'
elif isinstance(x, int):
the_list[i] = x -7
the_list
['GBP', 24, 'PIT', 18, 'Football']
對於一般情況,您可以為類型定義轉換字典:
d = {
int:lambda x: x-7,
list:lambda x: x[0]
}
my_list = ['GBP', 31, 'PIT', 25, ['Football']]
new_list = [d.get(type(item), lambda x: x)(item) for item in my_list]
print(new_list) # ['GBP', 24, 'PIT', 18, 'Football']
這種方法使您可以靈活地配置轉換並使它們緊湊。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.