Python:用一个字符串替换数组中的数字(Python: Replace a number in array with a string)
我有一个数字数组,我想根据某些条件用字符串替换。 我可以用数字替换它们:
d_sex = rand(10)
d_sex[d_sex > 0.5] = 1
d_sex[d_sex <= 0.5] = 0
d_sex
但我不能做d_sex[d_sex>0.5] = "F" 。 我将如何以最pythonic的方式做到这一点? 我会创建一个空字符串数组吗? 我正在寻找类似朱莉娅的东西:
d_sex = rand(50)
s_sex = ifelse(d_sex .> 0.5, "M", "F")
[d_sex s_sex]
I have an array of numbers, which I would like to replace with a string depending on some condition. I can replace them with numbers:
d_sex = rand(10)
d_sex[d_sex > 0.5] = 1
d_sex[d_sex <= 0.5] = 0
d_sex
But I cannot do d_sex[d_sex>0.5] = "F". How would I do that in the most pythonic way? Would I create an empty string array? I am looking for something similar to Julia's:
d_sex = rand(50)
s_sex = ifelse(d_sex .> 0.5, "M", "F")
[d_sex s_sex]
原文:https://stackoverflow.com/questions/27674880
更新时间:2020-01-24 19:08
相关问答
在str.replace您还可以传递一个可选的第三个参数( count ),用于处理正在完成的替换次数。 In [20]: strs = 'a;b;c;d'
In [21]: count = strs.count(";") - 1
In [22]: strs = strs.replace(';', ', ', count).replace(';', ' & ')
In [24]: strs
Out[24]: 'a, b, c & d'
帮助str.replace : S.replace(o
...
您可以使用字符串进行替换,其中索引toggels介于0和1之间。 var string = 'hello....';
console.log(string.replace(/\./g, (i => _ => '!?'[i = 1 - i])(1))); 有了一个对象。 var string = 'hello....';
console.log(string.replace(/\./g, (v => _ => v = { '!': '?', '?': '!' }[v])(
...
您可以使用替换正则表达式。 s/[;,\t\r ]|[\n]{2}/\n/g
s/在开始意味着搜索 [和]之间的字符是要搜索的字符(以任何顺序) 第二个/分隔搜索文本和替换文本 在英文中,这是: “搜索” ;或者,或\t或\r或 (空格)或正好两个顺序\n ,并将其替换为\n “ 在C#中,您可以执行以下操作:(导入System.Text.RegularExpressions ) Regex pattern = new Regex("[;,\t\r ]|[\n]{2}");
pattern.Re
...
你可以在str_replace()中使用数组 $str = str_replace(['Rob','Tom','Lee'],[1,7,5],$str);
You can use an array with str_replace() $str = str_replace(['Rob','Tom','Lee'],[1,7,5],$str);
如果我理解你的问题,这应该可以解决你的问题: $arr[0] = $firstletter; $output = implode(',',$arr) $arr[0] = $firstletter; $output = implode(',',$arr) If i understood your question correctly this should solve your problem: $arr[0] = $firstletter; $output = implode(',',$arr)
首先,你需要使用index()和replace()作为字符串方法,就像Martijn在评论中所说的那样。 这将是这样的: guess.index(i)在字符串guess找到i的索引。 您可能希望检查find() ,它将与index()执行相同操作,但在找不到子字符串时不会引发异常。 另请注意,您正在查看index()的结果是否在字符串guess 。 这是一个错误,因为整数不能在字符串中! index()返回一个整数! 然后考虑你说... and not guess.index(i) == gues
...
numpy.where相当于朱莉娅的ifelse : >>> np.where(d_sex > 0.5, 'M', 'F')
array(['F', 'M', 'M', 'F', 'F', 'M', 'F', 'M', 'F', 'F'],
dtype='|S1')
numpy.where is the equivalent of Julia's ifelse: >>> np.where(d_sex > 0.5, 'M', 'F')
array(['F', 'M', 'M', 'F', '
...
import re
import random
a = 'abc?def?ghi?jkl'
rand_max = 9
re.sub(r'\?', lambda x:str(random.randint(1,rand_max)), a)
# returns 'abc3def4ghi6jkl'
或没有正则表达式: import random
a = 'abc?def?ghi?jkl'
rand_max = 9
while '?' in a:
a = a[:a.index('?')] +
...