例如,我有一个包含字符串元素的数组,我只想要前三个字符:
public bool TryFetch<T>(string key, out T value)
{
var success = _store.ContainsKey(typeof(T)) && _store[typeof(T)].ContainsKey(key);
value = success ? this.Fetch<T>(key) : default(T);
return success;
}
public bool TryInject<T>(string key, Action<T> inject)
{
var success = this.TryFetch<T>(key, out T value);
if (success)
{
inject(value);
}
return success;
}
我该怎么做才能获得['app','foo','cow']
我尝试了以下操作,但不起作用
>>> import numpy
>>> a = numpy.array(['apples', 'foobar', 'cowboy'])
答案 0 :(得分:1)
import numpy
a = numpy.array(['apples', 'foobar', 'cowboy'])
v = list(a)
b = [val[:3] for val in v]
print(b)
>>> ['app', 'foo', 'cow']
答案 1 :(得分:1)
尝试像这样使用map
:
import numpy
a = numpy.array(['apples', 'foobar', 'cowboy'])
b = map(lambda string: string[:3], a)
print(b) # ['app', 'foo', 'cow']
使用此方法的好处是,如果您想对numpy
数组中的每个元素执行更复杂的操作,则可以定义一个更复杂的单参数函数,该函数接受来自该数组,然后吐出所需的数据,如下所示:
import numpy
def some_complex_func(element):
"""
Do some complicated things to element here.
"""
# In this case, only return the first three characters of each string
return element[:3]
a = numpy.array(['apples', 'foobar', 'cowboy'])
b = map(some_complex_func, a)
print(b) # ['app', 'foo', 'cow']
答案 2 :(得分:0)
尝试一下:
b = [a[i][:3] for i in range(len(a))]
print(b)
输出:
['app','foo','cow']