"蟒蛇方式"解析并有条件地取代2D列表中的每个元素 [英] "python way" to parse and conditionally replace every element in 2D list

查看:77
本文介绍了"蟒蛇方式"解析并有条件地取代2D列表中的每个元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有其中包括可能重新present字(以字母数字意义上的)字符串或整数,例如。

I have a list which consists of further lists of strings which may represent words(in the alphanumeric sense) or ints, e.g.

myLists = [['5','cat','23'], 
           ['33','parakeet','scalpel'], 
           ['correct','horse','battery','staple','99']]  

我要分析的阵列,因此再presentations所有的整数转换为整数。我有一个简单的功能,numParser(字符串)为此:

I want to parse the array so that all integer representations are converted to ints. I have a simple function, numParser(string) to this end:

def numParser(s):
    try:
        return int(s)
    except ValueError:
        return s

使用我的C / Java的背景我通常只通过两个数组迭代,改变每个值(一个事实,即这些阵列将是同质尽管)。但是,我是新来的蟒蛇,并认为有可能是一个更好的办法做到这一点,所以我搜索了一圈,发现一对夫妇就SO职位地图()和表融为一体prehension。名单COM prehension似乎并不喜欢去,因为列表是不统一的方式,但图()好像它应该工作。为了测试,我做了

With my c/java background I would normally just iterate through both arrays, changing each value (the fact that those arrays would be homogeneous notwithstanding). But I'm new to python and thought there might be a better way to do this, so I searched around and found a couple SO posts regarding map() and list comprehension. List comprehension didn't seem like the way to go because the lists aren't uniform, but map() seemed like it should work. To test, I did

a=['cat','5','4']
a = map(numParser, a)

其中一期工程。想也没想,我做了一个嵌套循环,没有不一样的。

Which works. Without thinking, I did the same on a nested loop, which did not.

for single_list in myLists:
    single_list = map(numParser, rawData)

现在,接收一个不变的二维数组后,它发生,我认为迭代器正在与该数组,而不是数组本身引用。 有一个超级时髦的蟒蛇的方式来完成转换所有整数重新presentations整数的我的目标,还是需要直接访问每个数组值来改变它,例如myLists [1] [2] = numParser(myLists [1] [2])

Now, after receiving an unchanged 2D array, it occurs to me that the iterator is working with references to the array, not the array itself. Is there a super snazzy python way to accomplish my goal of converting all integer representations to integers, or do I need to directly access each array value to change it, e.g. myLists[1][2] = numParser(myLists[1][2])?

推荐答案

下面是做到这一点的一种方法:

Here is one way to do it:

for single_list in myLists:
    for i, item in enumerate(single_list):
        single_list[i] = numParser(item)

这种方法的优点是你真正取代的元素在现有列表,而不是创造新的名单。

The advantage of this method is you actually replace the elements in the existing lists, not creating new lists.

这篇关于"蟒蛇方式"解析并有条件地取代2D列表中的每个元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆