Python - 在1和0之间的索引处更改数组的切换值

时间:2017-09-21 22:32:10

标签: python arrays python-3.x

我有一个像[[1,0,0,1]]这样的numpy数组。 我编写了以下方法来切换数组中特定索引的值,介于1和0之间:

const abbreviations = [
      { abbreviation: "d", expansion: "dog" },
      { abbreviation: "c", expansion: "cat" },
      { abbreviation: "h", expansion: "horse" }
    ];
    
    const testStringOriginal = "      blablablalbla,  / c  coOL @ d p  233c    ";
    
    const filterPattern1 = /[^a-zA-Z]+/g; // find all non English alphabetic characters.
    const filterPattern2 = /\b[a-zA-Z]{1,2}\b/g; // find words that are less then three characters long.
    const filterPattern3 = /\s\s+/g; // find multiple whitespace, tabs, newlines, etc.
    
    const filteredString = testStringOriginal
      .replace(filterPattern1, " ")
      // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replace#Specifying_a_function_as_a_parameter
      .replace(filterPattern2, match => {
        console.log("typeof: ", typeof match);
        abbreviations.forEach( item => {
          if (abbreviations.hasOwnProperty(item)) {
            if (match === item.abbreviation) {
              console.log("match YES!");
              console.log("match", match);
              console.log(
                "abbreviation in the object: ",
                item.abbreviation
              );
              return item.expansion; // return DOG, CAT or HORSE (if any match)
            } else {
              console.log("match - NO!");
              return "";
            }
          }
        });
        return match;
      })
      .replace(filterPattern3, " ")
      .trim() // remove leading and trailing whitespace.
      .toUpperCase(); // change string to upper case.
    console.log("ORGINAL STRING:" + testStringOriginal);
    console.log("CONVERTED STRING:" + filteredString);

所以,我不是python的每日用户,我得到这个错误:

'''
@param array: The array from which an value should be inverted
@param index: index at which the value should be inverted
'''
def change_binary_value(array, index):

    if array[index]==0:

        array[index] = 0
    else:
        array[index] = 1

好吧,我不想使用any()或all()。我只想改变一个值。为什么&python要让我这样做?这有点奇怪。

希望快速回答​​,

费边

1 个答案:

答案 0 :(得分:2)

在这种情况下,Numpy在数组中有数组,这就是为什么在数组之后提取第一个数组是必要的原因。

这是将在特定索引处反转值的代码(如果语句错误):

def change_binary_value(array, index):

    if array[0][index]==0:
        array[0][index] = 1
    else:
        array[0][index] = 0
    return array