Операция вычитания списка Python
Но это не поддерживается списками python Каков наилучший способ сделать это?
9 ответов
Используйте понимание списка:
Если вы хотите использовать синтаксис — infix, вы можете просто сделать:
вы можете использовать его, как:
Но если вам не нужны свойства списка (например, упорядочение), просто используйте наборы, как рекомендуют другие ответы.
Или вы можете просто установить x и y, чтобы вам не приходилось делать никаких преобразований.
Это операция «вычитания множества». Используйте для этого структуру данных.
Если проблемы с дублированием и упорядочением являются проблемой:
[i for i in a if not i in b or b.remove(i)]
Для многих случаев использования ответ, который вы хотите:
версия aaronasterling выполняет len(y) сравнение элементов для каждого элемента в x , поэтому требуется квадратичное время. Версия quantSoup использует наборы, поэтому для каждого элемента в x используется только один постоянный поиск по времени, но поскольку он преобразует как x , так и y в множества, он теряет порядок ваших элементов.
Преобразуя только y в набор и итерируя x по порядку, вы получаете лучшее из как линейного времени мира, так и сохранения порядка. *
Тем не менее, эта проблема по-прежнему имеет проблему с версией quantSoup: она требует, чтобы ваши элементы были хешируемыми. Это в значительной степени встроено в природу наборов. ** Если вы пытаетесь, например, вычесть список dicts из другого списка dicts, но список для вычитания большой, что вы делаете?
Если вы можете украсить свои ценности каким-то образом, что они хешируются, это решает проблему. Например, с плоским словарем, значения которого сами хешируются:
Если ваши типы немного сложнее (например, часто вы имеете дело с JSON-совместимыми значениями, которые являются хешируемыми или списками или dicts, значения которых рекурсивно одного типа), вы все равно можете использовать это решение. Но некоторые типы просто не могут быть преобразованы во что-нибудь хешируемое.
Если ваши элементы не являются и не могут быть сделаны хешируемыми, но они сопоставимы, вы можете, по крайней мере, получить лог-линейное время ( O(N*log M) , что намного лучше, чем время O(N*M) решение списка, но не так хорошо, как время O(N+M) заданного решения) путем сортировки и использования bisect :
Если ваши элементы не являются ни хешируемыми, ни сопоставимыми, вы зацикливаетесь на квадратичном решении.
* Обратите внимание, что вы также можете сделать это, используя пару объектов OrderedSet , для которых вы можете найти рецепты и сторонние модули. Но я думаю, что это проще.
** По умолчанию набор запросов — это постоянное время, так как все, что ему нужно сделать, это хэш-значение и посмотреть, есть ли запись для этого хэша. Если он не может присвоить значение, это не сработает.
Операция вычитания списка Python
но это не поддерживается списками python
Каков наилучший способ сделать это?
10 ответов:
использовать список понимание:
если вы хотите использовать — синтаксис инфикса, вы можете просто сделать:
затем вы можете использовать его как:
но если вам абсолютно не нужны свойства списка (например, порядок), просто используйте наборы, как рекомендуют другие ответы.
использовать установить разницу
или у вас могут быть только X и y, поэтому вам не нужно делать никаких преобразований.
это операция» set subtraction». Используйте для этого заданную структуру данных.
В Python 2.7:
выход:
Если дублировать и заказывать детали проблема:
[i for i in a if not i in b or b.remove(i)]
для многих случаев использования, ответ вы хотите:
это гибрид между aaronasterling это и ответ quantumSoup.
версия aaronasterling делает len(y) сравнение элементов для каждого элемента в x , так что это занимает квадратичное время. версия quantumSoup использует наборы, поэтому она выполняет один поиск набора констант для каждого элемента в x -но, потому что он преобразует и x и y в наборы, он теряет порядок ваших элементов.
путем преобразования только y в набор, и перебор x для того, чтобы вы получили лучшее из обоих миров-линейное время и сохранение порядка.*
однако у этого все еще есть проблема с версией quantumSoup: она требует, чтобы ваши элементы были хэшируемыми. Это в значительной степени встроено в природу наборов.** Если вы пытаетесь, например, вычесть список диктов из другого списка диктов, но список чтобы вычесть большой, что вы делаете?
если вы можете украсить ваши ценности в некотором роде, что они hashable, что решает проблему. Например, с плоским словарем, значения которого сами хешируются:
если видов немного более сложных (например, часто вы имеете дело с JSON-совместимые значения, которые hashable, или списки или словарь, значения которых являются рекурсивно тот же тип), вы все еще можете использовать это решение. Но некоторые типы просто не могут быть преобразуется во что-нибудь хэшируемое.
если ваши элементы не, и не может быть сделано, hashable, но они сопоставимы, можно как минимум получить лог-линейного времени ( O(N*log M) , что намного лучше, чем O(N*M) время решения списка, но не так хорошо, как O(N+M) время заданного решения) путем сортировки и использования bisect :
если ваши товары не hashable, ни сравнима, то вы застряли с квадратичной решение.
* обратите внимание, что вы также можете сделать это с помощью пары OrderedSet объекты, для которых можно найти рецепты и сторонних модулей. Но я думаю, что это проще.
** причина, по которой поиск настроек является постоянным временем, заключается в том, что все, что ему нужно сделать, это хэшировать значение и посмотреть, есть ли запись для этого хэша. Если он не может хэшировать значение, это не будет работать.
Оператор вычитания Python
Python предоставляет оператор вычитания – вычесть один объект от другого. Семантика вычитания зависит от типов данных операндов. Например, вычитание двух целых чисел выполняет операцию арифметической разности, тогда как вычитание двух наборов выполняет операцию набора разности. Конкретное возвращаемое значение оператора минус определяется в данных … Оператор вычитания Python Подробнее »
- Автор записи
Автор оригинала: Chris.
Python предоставляет оператор вычитания — вычесть один объект из другого. Семантика вычитания зависит от типов данных операндов. Например, вычитание двух целых чисел выполняет Арифметическая разница Операция, тогда как вычитание двух наборов выполняет Установить разницу операция. Конкретное возвращаемое значение оператора минус определяется в типах данных « __sub __ () магический метод.
Посмотрите на следующие примеры!
Примеры
Оператор на целочисленных операндах дает еще одно целое – математическое Разница обоих операндов:
Если хотя бы один из операндов – это значение поплавка, результат также является поплавком, является инфекционным!
Вы также можете выполнить оператор вычитания на Python наборы Отказ В этом случае он рассчитывает Установить разницу , то есть, он создает новый набор элементов в первом, но не во втором операнде.
Что если два операнда имеют несовместимый тип данных? Например, если вы попытаетесь вычесть набор из строки?
Результат несовместимого добавления является Типеррор Отказ Вы можете исправить его, используя только совместимые типы данных для операции.
Можете ли вы использовать оператор вычитания на пользовательских объектах? Да!
Магический метод вычитания Python
Чтобы использовать оператор вычитания на пользовательских объектах, определите __sub __ () Дундер Метод, который занимает два аргумента: Я и Другое и возвращает результат Я — другие Отказ Вы можете определить конкретное поведение, используя атрибуты (данные), поддерживаемые в этом объекте.
В следующем коде вы создаете корзину из <«Кофе», «Банан», «Хлеб»>Но затем вы удалите содержимое в другой корзине <«CRED»>Из него – например, чтобы предотвратить двойную покупку:
Выход этого фрагмента кода является новой корзиной:
Код состоит из следующих шагов:
- Создать класс Корзина Это содержит содержимое списка для хранения некоторых товаров.
- Определите магический метод __sub__ Это создает новую корзину, сочетая наборы товаров от корзин двух операндов. Обратите внимание, что мы полагаемся на уже реализованный оператор вычитания на множествах, то есть Установить разницу , чтобы на самом деле реализовать оператор вычитания для корзин.
- Мы создаем две корзины My_Basket и to_remove и рассчитайте разницу между ними к новой корзине updated_basket Отказ
Вы можете вычесть списки в Python?
Python не позволяет встроенную поддержку для Разница в списке Операция , то есть, создавая новый список с элементами из первого списка операнда Но без элементов из второго списка операнда. Вместо этого, чтобы вычесть lst_2 из списка lst_1 Используйте оператор понимания списка как фильтр [x для x в lst_1, если x не в lst_2] Отказ
Вот пример кода:
Этот код использует понимание списка, который является компактным способом создания списков. Простая формула – [Выражение + контекст] Отказ
- Выражение: Что делать с каждым элементом списка?
- Контекст: Какие элементы для выбора? Контекст состоит из произвольного количества для и Если заявления.
Вы можете узнать больше о понимании списка в этом углубленном уроке с видео:
*** Список понимания – Ultimate Guide ***
Но прежде чем мы будем двигаться дальше, я рад представить вам мою новую книгу Python Python One-listers (Amazon Link).
Если вам нравятся одноклассники, вы будете любить книгу. Это научит вам все, что нужно знать о Одно строка кода Python. Но это тоже Введение в компьютерную науку , наука о данных, машин обучения и алгоритмы. Вселенная в одной строке Python!
Книга была выпущена в 2020 году с помощью книги по программированию мирового класса Nostarch Press (San Francisco).
Программа вычитания Python с пользовательским входом
Чтобы создать простую программу вычитания в Python, принимая ввод пользователя и вычитание предоставленных номеров, вы можете использовать следующие четыре шага:
- Получите ввод пользователя в виде строки с помощью встроенного вход () Функция и хранить результат в переменных num_1 и num_2 Отказ
- Преобразовать входы пользователей строки к численным типам, используя, например, int () или поплавок () конструкторы.
- Вычте численные значения с использованием оператора вычитания num_1 — num_2 Отказ
- Распечатайте результат к оболочке Python.
Вот эти четыре шага в Python код:
Вот пример выполнения кода, где я помещаю в целые числа 44 и 2, и рассчитал разницу с использованием оператора вычитания:
Сторирование оператора вычитания Python
Вы можете объединить два оператора вычитания. Например, выражение X – Y – Z сначала рассчитал разницу между х и y а затем вычесть z из полученного объекта. Таким образом, это семантически идентично ( (X – Y) – Z) Отказ
Вот минимальный пример:
Арифметические операторы
Арифметические операторы – синтаксические ярлыки для выполнения основных математических операций по номерам.
Оператор | Имя | Описание | Пример |
+ | Добавление | Расчет суммы двух операндов | 3 + 4 |
– | Вычитание | Вычитание второго операнда с первого операнда | 4 – 3 |
* | Умножение | Умножить первый со вторым операндом | 3 * 4 |
/ | Разделение | Разделение первого на второй операнд | 3 / 4.75 |
% | Модуль | Расчет остатка при делите первого на второй операнд | 7 % 4 |
// | Целочисленное разделение, напольное разделение | Разделение первого операнда на второй операнд и закругление результата до следующего целого числа | 8 // 3 |
** | Экспонент | Поднимая первый операнд на силу второго операнда | 2 ** 3 |
Работая в качестве исследователя в распределенных системах, доктор Кристиан Майер нашел свою любовь к учению студентов компьютерных наук.
Чтобы помочь студентам достичь более высоких уровней успеха Python, он основал сайт программирования образования Finxter.com Отказ Он автор популярной книги программирования Python одноклассники (Nostarch 2020), Coauthor of Кофе-брейк Python Серия самооставленных книг, энтузиаста компьютерных наук, Фрилансера и владелец одного из лучших 10 крупнейших Питон блоги по всему миру.
Его страсти пишут, чтение и кодирование. Но его величайшая страсть состоит в том, чтобы служить стремлению кодер через Finxter и помогать им повысить свои навыки. Вы можете присоединиться к его бесплатной академии электронной почты здесь.
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, …
chain(‘ABC’, ‘DEF’) —> A B C D E F
p0, p1, … plast, q0, q1, …
chain.from_iterable([‘ABC’, ‘DEF’]) —> A B C D E F
(d[0] if s[0]), (d[1] if s[1]), …
compress(‘ABCDEF’, [1,0,1,0,1,1]) —> A C E F
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
zip_longest(‘ABCD’, ‘xy’, fillvalue=’-‘) —> Ax By C- D-
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.