кастинг Объектного массива к Целочисленной ошибке массива

С точки зрения эффективности Вы не собираетесь биться

s.translate(None, string.punctuation)

Для старших версий использования Python следующий код:

s.translate(str.maketrans('', '', string.punctuation))

Это выполняет необработанные строковые операции в C с таблицей поиска - нет очень, который разобьет это, но запись Вашего собственного кода C.

, Если скорость не является беспокойством, другая опция, хотя:

exclude = set(string.punctuation)
s = ''.join(ch for ch in s if ch not in exclude)

Это быстрее, чем s.replace с каждым символом, но не будет работать, а также нечистые подходы Python, такие как regexes или string.translate, как Вы видите от ниже синхронизаций. Для этого типа проблемы, делая его на максимально низком уровне платит прочь.

Код времени:

import re, string, timeit

s = "string. With. Punctuation"
exclude = set(string.punctuation)
table = string.maketrans("","")
regex = re.compile('[%s]' % re.escape(string.punctuation))

def test_set(s):
    return ''.join(ch for ch in s if ch not in exclude)

def test_re(s):  # From Vinko's solution, with fix.
    return regex.sub('', s)

def test_trans(s):
    return s.translate(table, string.punctuation)

def test_repl(s):  # From S.Lott's solution
    for c in string.punctuation:
        s=s.replace(c,"")
    return s

print "sets      :",timeit.Timer('f(s)', 'from __main__ import s,test_set as f').timeit(1000000)
print "regex     :",timeit.Timer('f(s)', 'from __main__ import s,test_re as f').timeit(1000000)
print "translate :",timeit.Timer('f(s)', 'from __main__ import s,test_trans as f').timeit(1000000)
print "replace   :",timeit.Timer('f(s)', 'from __main__ import s,test_repl as f').timeit(1000000)

Это дает следующие результаты:

sets      : 19.8566138744
regex     : 6.86155414581
translate : 2.12455511093
replace   : 28.4436721802
65
задан Draken 29 May 2017 в 14:19
поделиться

2 ответа

You can't cast an Object array to an Integer array. You have to loop through all elements of a and cast each one individually.

Object[] a = new Object[1];
Integer b=1;
a[0]=b;
Integer[] c = new Integer[a.length];
for(int i = 0; i < a.length; i++)
{
    c[i] = (Integer) a[i];
}

Edit: I believe the rationale behind this restriction is that when casting, the JVM wants to ensure type-safety at runtime. Since an array of Objects can be anything besides Integers, the JVM would have to do what the above code is doing anyway (look at each element individually). The language designers decided they didn't want the JVM to do that (I'm not sure why, but I'm sure it's a good reason).

However, you can cast a subtype array to a supertype array (e.g. Integer[] to Object[])!

21
ответ дан 24 November 2019 в 15:23
поделиться
java.lang.ClassCastException: [Ljava.lang.Object; cannot be cast to [Ljava.lang.Integer;

you try to cast an Array of Object to cast into Array of Integer. You cant do it. This type of downcast is not permitted.

You can make an array of Integer, and after that copy every value of the first array into second array.

4
ответ дан 24 November 2019 в 15:23
поделиться
Другие вопросы по тегам:

Похожие вопросы: