Перейти к содержимому

Как соединить цифры в питоне

  • автор:

Объединить два целых числа в Python

Как я могу объединить два целочисленных числа (например, 10 и 20) в Python и иметь число 1020.

10 ответов

Лучший способ сделать это в python был указан в принятом ответе, но если вы хотите сделать это в шаблонах jinja2 — оператор конкатенации

дает вам аккуратный способ сделать это, так как он ищет представление unicode из всех объектов, таким образом, вы можете «конкатенировать целые числа».

То есть вы можете это сделать (учитывая a=10 и b=20 ):

Вставьте оба значения в строку, объедините строки и затем верните результат в целое число:

Использование математики, вероятно, быстрее, чем решения, которые преобразуются в str и обратно:

Если вы можете принять двухзначное второе число:

Хотя вам, вероятно, понадобятся некоторые проверки, включенные для проверки второго номера не более двух цифр. Или, если вашим вторым номером может быть любое количество цифр, вы можете сделать что-то вроде этого:

Однако эта версия не позволяет объединять числа, такие как 03 и 02, чтобы получить 0302. Для этого вам нужно либо добавить аргументы, чтобы указать количество цифр в каждом целочисленном, либо использовать строки.

Как правильно объединить несколько распознанных цифр?

Помогите кому не сложно пожалуйста, мне надо чтобы программа в одном коде распознавала несколько цифр, как правильно объединить их??

у меня есть код на 5

Как правильно объединить несколько программ
Имеется несколько простых программ в каждой по одной главной форме и несколько вспомогательных форм.

Как объединить несколько checkbox?
Всем привет. В JS не силен, не могу ни как разобраться. В общем есть код .

Как объединить несколько ContextMenu?
Приветствую! Есть окно, у окна ContextMenu. В окне есть кнопка, у которой тоже ContextMenu. При.

Как объединить несколько запросов?
есть несколько запросов вида: SELECT SUM(summa), COUNT(1) FROM kassa where id_kassa=1 .

Сообщение от Pike111

То есть в итоге код должен запоминать веса сразу двух цифр и распознавать так (?):

Собственно, для этого просто нужно сделать, чтобы сеть записывала веса сразу всех нужных вам цифр.
Если не рефакторить код, а просто показать как это может быть:

Сообщение от Garry Galler

Как объединить несколько коллекций?
Делаю для тренировке игру. у меня есть несколько классов под каждый класс есть свой лист в котором.

Как объединить несколько изображений в одно?
Здравствуйте! Стоит задача сделать программу которая будет при загрузке в неё изображений (JPG).

Как объединить несколько сложных запросов?
Есть такой запрос который выводит данные по id (R_PERS_ACCOUNT_ID) и дате (MAX(RBS.CREATE_DATE)) .

Как объединить несколько .xls в одну?
Имеется очень много книг .xls в разных подпапках одной папки. Имена книг .xls могут совпадать. В.

Как объединить несколько установочных файлов в 1?
Доброго времени суток! Возникла такая ситуация: нужно объединить множество файлов установки в 1.

Как объединить несколько столбцов в один?
Нужно чтобы SQL запрос, из трёх атрибутов, сливал всё в одно. Допустим есть таблица.

Как соединить цифры в питоне

How do I concatenate two integer numbers in Python? For example, given 10 and 20 , I’d like a returned value of 1020 .

khelwood's user avatar

17 Answers 17

Cast both to a string, concatenate the strings and then cast the result back to an integer:

Konstantin Dinev's user avatar

Using math is probably faster than solutions that convert to str and back:

If you can assume a two digit second number:

Although, you probably would want some checks included to verify the second number is not more than two digits. Or, if your second number can be any number of digits, you could do something like this:

This version however, does not allow you to merge numbers like 03 and 02 to get 0302. For that you would need to either add arguments to specify the number of digits in each integer, or use strings.

Как объединить два целых числа в Python?

Как объединить два целых числа в Python? Например, учитывая 10 и 20 , я хотел бы получить возвращаемое значение «1020» .

14 ответы

Приведите оба к строке, соедините строки, а затем верните результат обратно в целое число:

ответ дан 01 дек ’12, 07:12

Использование математики, вероятно, быстрее, чем решения, которые преобразуются в str и обратно:

Если вы можете предположить двузначное второе число:

Хотя вы, вероятно, захотите включить некоторые проверки, чтобы убедиться, что второе число не больше двух цифр. Или, если ваше второе число может состоять из любого количества цифр, вы можете сделать что-то вроде этого:

Эта версия, однако, не позволяет вам объединять числа, такие как 03 и 02, чтобы получить 0302. Для этого вам нужно либо добавить аргументы, чтобы указать количество цифр в каждом целом, либо использовать строки.

ответ дан 27 мар ’21, в 20:03

вам не кажется, что импорт математики замедлит работу? — никто

@gokcehan Да, но если бы вы вызывали эту функцию много раз в цикле, время импорта математики было бы незначительным — Мэтт

Кроме того, это имеет больше смысла математически, чем манипуляции со строками. — пользователь395760

Почему бы не использовать ceil Вместо того, чтобы использовать floor и добавить один? — мбомба007

@mbomb007 ceil(num) != floor(num) + 1 для всех num . В частности, если num является целым числом, то ceil(num) == floor(num) . Если вы заменили floor()+1 с ceil() функция не будет работать должным образом, если вторым аргументом будет целая степень числа 10. (Поскольку log10(10^n) = n вы находитесь в том случае, когда floor(n) == ceil(n) ) — Мэтт

Пример 1: (Пример 2 намного быстрее, не говорите, что я вас не предупреждал!)

Пример 2:

Для людей, думающих eval это «зло», вот еще один способ сделать это:

EDIT:

Я подумал, что было бы удобно синхронизировать эти коды, смотрите ниже:

Вывод:

Наблюдения и советы этой статьи мы подготовили на основании опыта команды оригинальный ответ выглядит больше удобочитаемый, но если вам нужно хорошая скорость, выберите int(f’ ‘)

itertools — Functions creating iterators for efficient looping¶

This module implements a number of iterator building blocks inspired by constructs from APL, Haskell, and SML. Each has been recast in a form suitable for Python.

The module standardizes a core set of fast, memory efficient tools that are useful by themselves or in combination. Together, they form an “iterator algebra” making it possible to construct specialized tools succinctly and efficiently in pure Python.

For instance, SML provides a tabulation tool: tabulate(f) which produces a sequence f(0), f(1), . . The same effect can be achieved in Python by combining map() and count() to form map(f, count()) .

These tools and their built-in counterparts also work well with the high-speed functions in the operator module. For example, the multiplication operator can be mapped across two vectors to form an efficient dot-product: sum(starmap(operator.mul, zip(vec1, vec2, strict=True))) .

Infinite iterators:

start, start+step, start+2*step, …

count(10) —> 10 11 12 13 14 .

p0, p1, … plast, p0, p1, …

cycle(‘ABCD’) —> A B C D A B C D .

elem, elem, elem, … endlessly or up to n times

repeat(10, 3) —> 10 10 10

Iterators terminating on the shortest input sequence:

accumulate([1,2,3,4,5]) —> 1 3 6 10 15

p0, p1, … plast, q0, q1, …

p0, p1, … plast, q0, q1, …

(d[0] if s[0]), (d[1] if s[1]), …

seq[n], seq[n+1], starting when pred fails

dropwhile(lambda x: x<5, [1,4,6,4,1]) —> 6 4 1

elements of seq where pred(elem) is false

filterfalse(lambda x: x%2, range(10)) —> 0 2 4 6 8

sub-iterators grouped by value of key(v)

seq, [start,] stop [, step]

elements from seq[start:stop:step]

islice(‘ABCDEFG’, 2, None) —> C D E F G

pairwise(‘ABCDEFG’) —> AB BC CD DE EF FG

starmap(pow, [(2,5), (3,2), (10,3)]) —> 32 9 1000

seq[0], seq[1], until pred fails

takewhile(lambda x: x<5, [1,4,6,4,1]) —> 1 4

it1, it2, … itn splits one iterator into n

Combinatoric iterators:

cartesian product, equivalent to a nested for-loop

r-length tuples, all possible orderings, no repeated elements

r-length tuples, in sorted order, no repeated elements

r-length tuples, in sorted order, with repeated elements

AA AB AC AD BA BB BC BD CA CB CC CD DA DB DC DD

AB AC AD BA BC BD CA CB CD DA DB DC

AB AC AD BC BD CD

AA AB AC AD BB BC BD CC CD DD

Itertool functions¶

The following module functions all construct and return iterators. Some provide streams of infinite length, so they should only be accessed by functions or loops that truncate the stream.

itertools. accumulate ( iterable [ , func , * , initial=None ] ) ¶

Make an iterator that returns accumulated sums, or accumulated results of other binary functions (specified via the optional func argument).

If func is supplied, it should be a function of two arguments. Elements of the input iterable may be any type that can be accepted as arguments to func. (For example, with the default operation of addition, elements may be any addable type including Decimal or Fraction .)

Usually, the number of elements output matches the input iterable. However, if the keyword argument initial is provided, the accumulation leads off with the initial value so that the output has one more element than the input iterable.

Roughly equivalent to:

There are a number of uses for the func argument. It can be set to min() for a running minimum, max() for a running maximum, or operator.mul() for a running product. Amortization tables can be built by accumulating interest and applying payments:

See functools.reduce() for a similar function that returns only the final accumulated value.

New in version 3.2.

Changed in version 3.3: Added the optional func parameter.

Changed in version 3.8: Added the optional initial parameter.

Make an iterator that returns elements from the first iterable until it is exhausted, then proceeds to the next iterable, until all of the iterables are exhausted. Used for treating consecutive sequences as a single sequence. Roughly equivalent to:

Alternate constructor for chain() . Gets chained inputs from a single iterable argument that is evaluated lazily. Roughly equivalent to:

Return r length subsequences of elements from the input iterable.

The combination tuples are emitted in lexicographic ordering according to the order of the input iterable. So, if the input iterable is sorted, the output tuples will be produced in sorted order.

Elements are treated as unique based on their position, not on their value. So if the input elements are unique, there will be no repeated values in each combination.

Roughly equivalent to:

The code for combinations() can be also expressed as a subsequence of permutations() after filtering entries where the elements are not in sorted order (according to their position in the input pool):

The number of items returned is n! / r! / (n-r)! when 0 <= r <= n or zero when r > n .

itertools. combinations_with_replacement ( iterable , r ) ¶

Return r length subsequences of elements from the input iterable allowing individual elements to be repeated more than once.

The combination tuples are emitted in lexicographic ordering according to the order of the input iterable. So, if the input iterable is sorted, the output tuples will be produced in sorted order.

Elements are treated as unique based on their position, not on their value. So if the input elements are unique, the generated combinations will also be unique.

Roughly equivalent to:

The code for combinations_with_replacement() can be also expressed as a subsequence of product() after filtering entries where the elements are not in sorted order (according to their position in the input pool):

The number of items returned is (n+r-1)! / r! / (n-1)! when n > 0 .

New in version 3.1.

Make an iterator that filters elements from data returning only those that have a corresponding element in selectors that evaluates to True . Stops when either the data or selectors iterables has been exhausted. Roughly equivalent to:

New in version 3.1.

Make an iterator that returns evenly spaced values starting with number start. Often used as an argument to map() to generate consecutive data points. Also, used with zip() to add sequence numbers. Roughly equivalent to:

When counting with floating point numbers, better accuracy can sometimes be achieved by substituting multiplicative code such as: (start + step * i for i in count()) .

Changed in version 3.1: Added step argument and allowed non-integer arguments.

Make an iterator returning elements from the iterable and saving a copy of each. When the iterable is exhausted, return elements from the saved copy. Repeats indefinitely. Roughly equivalent to:

Note, this member of the toolkit may require significant auxiliary storage (depending on the length of the iterable).

itertools. dropwhile ( predicate , iterable ) ¶

Make an iterator that drops elements from the iterable as long as the predicate is true; afterwards, returns every element. Note, the iterator does not produce any output until the predicate first becomes false, so it may have a lengthy start-up time. Roughly equivalent to:

Make an iterator that filters elements from iterable returning only those for which the predicate is false. If predicate is None , return the items that are false. Roughly equivalent to:

Make an iterator that returns consecutive keys and groups from the iterable. The key is a function computing a key value for each element. If not specified or is None , key defaults to an identity function and returns the element unchanged. Generally, the iterable needs to already be sorted on the same key function.

The operation of groupby() is similar to the uniq filter in Unix. It generates a break or new group every time the value of the key function changes (which is why it is usually necessary to have sorted the data using the same key function). That behavior differs from SQL’s GROUP BY which aggregates common elements regardless of their input order.

The returned group is itself an iterator that shares the underlying iterable with groupby() . Because the source is shared, when the groupby() object is advanced, the previous group is no longer visible. So, if that data is needed later, it should be stored as a list:

groupby() is roughly equivalent to:

Make an iterator that returns selected elements from the iterable. If start is non-zero, then elements from the iterable are skipped until start is reached. Afterward, elements are returned consecutively unless step is set higher than one which results in items being skipped. If stop is None , then iteration continues until the iterator is exhausted, if at all; otherwise, it stops at the specified position.

If start is None , then iteration starts at zero. If step is None , then the step defaults to one.

Unlike regular slicing, islice() does not support negative values for start, stop, or step. Can be used to extract related fields from data where the internal structure has been flattened (for example, a multi-line report may list a name field on every third line).

Roughly equivalent to:

Return successive overlapping pairs taken from the input iterable.

The number of 2-tuples in the output iterator will be one fewer than the number of inputs. It will be empty if the input iterable has fewer than two values.

Roughly equivalent to:

New in version 3.10.

Return successive r length permutations of elements in the iterable.

If r is not specified or is None , then r defaults to the length of the iterable and all possible full-length permutations are generated.

The permutation tuples are emitted in lexicographic order according to the order of the input iterable. So, if the input iterable is sorted, the output tuples will be produced in sorted order.

Elements are treated as unique based on their position, not on their value. So if the input elements are unique, there will be no repeated values within a permutation.

Roughly equivalent to:

The code for permutations() can be also expressed as a subsequence of product() , filtered to exclude entries with repeated elements (those from the same position in the input pool):

The number of items returned is n! / (n-r)! when 0 <= r <= n or zero when r > n .

itertools. product ( * iterables , repeat = 1 ) ¶

Cartesian product of input iterables.

Roughly equivalent to nested for-loops in a generator expression. For example, product(A, B) returns the same as ((x,y) for x in A for y in B) .

The nested loops cycle like an odometer with the rightmost element advancing on every iteration. This pattern creates a lexicographic ordering so that if the input’s iterables are sorted, the product tuples are emitted in sorted order.

To compute the product of an iterable with itself, specify the number of repetitions with the optional repeat keyword argument. For example, product(A, repeat=4) means the same as product(A, A, A, A) .

This function is roughly equivalent to the following code, except that the actual implementation does not build up intermediate results in memory:

Before product() runs, it completely consumes the input iterables, keeping pools of values in memory to generate the products. Accordingly, it is only useful with finite inputs.

itertools. repeat ( object [ , times ] ) ¶

Make an iterator that returns object over and over again. Runs indefinitely unless the times argument is specified.

Roughly equivalent to:

A common use for repeat is to supply a stream of constant values to map or zip:

Make an iterator that computes the function using arguments obtained from the iterable. Used instead of map() when argument parameters are already grouped in tuples from a single iterable (when the data has been “pre-zipped”).

The difference between map() and starmap() parallels the distinction between function(a,b) and function(*c) . Roughly equivalent to:

Make an iterator that returns elements from the iterable as long as the predicate is true. Roughly equivalent to:

Return n independent iterators from a single iterable.

The following Python code helps explain what tee does (although the actual implementation is more complex and uses only a single underlying FIFO queue):

Once a tee() has been created, the original iterable should not be used anywhere else; otherwise, the iterable could get advanced without the tee objects being informed.

tee iterators are not threadsafe. A RuntimeError may be raised when using simultaneously iterators returned by the same tee() call, even if the original iterable is threadsafe.

This itertool may require significant auxiliary storage (depending on how much temporary data needs to be stored). In general, if one iterator uses most or all of the data before another iterator starts, it is faster to use list() instead of tee() .

itertools. zip_longest ( * iterables , fillvalue = None ) ¶

Make an iterator that aggregates elements from each of the iterables. If the iterables are of uneven length, missing values are filled-in with fillvalue. Iteration continues until the longest iterable is exhausted. Roughly equivalent to:

If one of the iterables is potentially infinite, then the zip_longest() function should be wrapped with something that limits the number of calls (for example islice() or takewhile() ). If not specified, fillvalue defaults to None .

Itertools Recipes¶

This section shows recipes for creating an extended toolset using the existing itertools as building blocks.

The primary purpose of the itertools recipes is educational. The recipes show various ways of thinking about individual tools — for example, that chain.from_iterable is related to the concept of flattening. The recipes also give ideas about ways that the tools can be combined — for example, how compress() and range() can work together. The recipes also show patterns for using itertools with the operator and collections modules as well as with the built-in itertools such as map() , filter() , reversed() , and enumerate() .

A secondary purpose of the recipes is to serve as an incubator. The accumulate() , compress() , and pairwise() itertools started out as recipes. Currently, the iter_index() recipe is being tested to see whether it proves its worth.

Substantially all of these recipes and many, many others can be installed from the more-itertools project found on the Python Package Index:

Many of the recipes offer the same high performance as the underlying toolset. Superior memory performance is kept by processing elements one at a time rather than bringing the whole iterable into memory all at once. Code volume is kept small by linking the tools together in a functional style which helps eliminate temporary variables. High speed is retained by preferring “vectorized” building blocks over the use of for-loops and generator s which incur interpreter overhead.

Как соединить цифры в питоне

Math module in Python contains a number of mathematical operations, which can be performed with ease using the module. math.comb() method in Python is used to get the number of ways to choose k items from n items without repetition and without order. It basically evaluates to n! / (k! * (n – k)!) when k n. It is also known as binomial coefficient because it is equivalent to the coefficient of k-th term in polynomial expansion of the expression (1 + x) n .
This method is new in Python version 3.8.

Parameters:
n: A non-negative integer
k: A non-negative integer

Returns: an integer value which represents the number of ways to choose k items from n items without repetition and without order.

How can I concatenate two integers in Python?

How do I concatenate two integer numbers in Python? For example, given 10 and 20 , I’d like a returned value of 1020 .

khelwood's user avatar

17 Answers 17

Cast both to a string, concatenate the strings and then cast the result back to an integer:

Konstantin Dinev's user avatar

Using math is probably faster than solutions that convert to str and back:

If you can assume a two digit second number:

Although, you probably would want some checks included to verify the second number is not more than two digits. Or, if your second number can be any number of digits, you could do something like this:

This version however, does not allow you to merge numbers like 03 and 02 to get 0302. For that you would need to either add arguments to specify the number of digits in each integer, or use strings.

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *