def front_back(a, b):
# +++your code here+++
if len(a) % 2 == 0 && len(b) % 2 == 0:
return a[:(len(a)/2)] + b[:(len(b)/2)] + a[(len(a)/2):] + b[(len(b)/2):]
else:
#todo! Not yet done. :P
return
파이썬 /dev/raw/raw1 '와' 와 '또는' 조건문.
예:
if foo == 'abc' and bar == 'bac' or zoo == '123':
# do something
>. # 39 i& 오류가 발생하는 경우, m 의 조건부. 내가 왜 그래?
것은 있을 수 없는 ',', '에서' SyntaxError & & 연산자입니다 파이썬. 거짓하였으니 '' 와 '!' 이 파이썬 유효하지 않은 것으로 알려졌다.
일부 다른 언어 연산자는 선택하는 알 수 있는 다른 이름을 가지고 있다. 논리 연산자 ',' 와 ',' 실제로 & & 불렀으매 '와' 와 '또는'. 논리 연산자 '부정' 아닌 '거짓하였으니!' 라고 합니다.
그래서 그냥 쓸 수 있습니다.
if len(a) % 2 == 0 and len(b) % 2 == 0:
심지어:
if not (len(a) % 2 or len(b) % 2):
내가 대한 작동자 " equivalents"; 이 table:
<! - 언어: > 없음 -;
+------------------------------+---------------------+
| Operator (other languages) | Operator (Python) |
+==============================+=====================+
| && | and |
+------------------------------+---------------------+
| || | or |
+------------------------------+---------------------+
| ! | not |
+------------------------------+---------------------+
참조 [파이썬 문서: 6.11. 부울입니다 운영체] (https://docs.python.org/reference/expressions.html # 부울입니다 운영체).
Python 역시 목동들과 논리 연산자 (비트 / 이항 연산자:
<! - 언어: > 없음 -;
+--------------------+--------------------+
| Logical operator | Bitwise operator |
+====================+====================+
| and | & |
+--------------------+--------------------+
| or | | |
+--------------------+--------------------+
Python 에서 부정 (비트 없다 (그냥 비트단위 보색으로 연산자입니다 않을 수 없는 '~' - ' avamer 그것은').
참조 [6.6. 단항 산술 및 비트 / 바이너리 운영체] (https://docs.python.org/3/reference/expressions.html # 단항 산술 및 비트 운영) 및 [6.7. 이진 산술 연산을] (https://docs.python.org/reference/expressions.html # 이진 산술 연산을).
논리 연산자 (주로 많은 다른 언어로) 은 그것은꿈의 단락 있다는 장점이 있습니다. 즉, 그 결과, 두 번째는 첫 번째 피연산자 경우 이미 eventtest 작동자 isn& # 39, 평가하실 전혀 없다.
이 기능을 사용할 수 있는 데, 단순히 내가 표시하십시오 정보기술 (it) 과 다시 되돌려줍니다 값을 보여준다. 이것은 실제로 편리하게 확인할 수 있습니다 평가하실 슬픔으로창백해지고 인쇄하십시오 명령문입니다:
>>> def print_and_return(value):
... print(value)
... return value
>>> res = print_and_return(False) and print_and_return(True)
False
하나만 볼 수 있듯이, t # 39 는 파이썬 상행담관염이라고 didn& 기술서임을 인쇄하십시오 실행됨을 도왔으매 쳐다보지도 오른쪽 피연산자를.
이항 연산자 대한 이 경우는 그렇지 않다. 이들은 모두 항상 평가하십시오 피연산자로:
>>> res = print_and_return(False) & print_and_return(True);
False
True
>>> res = print_and_return(True) and print_and_return(False);
True
False
이 여기 다른 Table:) 를 요약하십시오.
<! - 언어: > 없음 -;
+-----------------+-------------------------+
| Expression | Right side evaluated? |
+=================+=========================+
| `True` and ... | Yes |
+-----------------+-------------------------+
| `False` and ... | No |
+-----------------+-------------------------+
| `True` or ... | No |
+-----------------+-------------------------+
| `False` or ... | Yes |
+-----------------+-------------------------+
'True' 와 '거짓' 을 나타내는 뭐라구오 부울 (왼쪽 측) ',' 진정한 '또는' t # 39, 그들은 되돌려줍니다 don& 해야 할 때, 그들은 단지 'True' 또는 '거짓' 거짓 '복귀하십시오 그들에 대한 sup> <; (1)', '부울 호출됨 < sup>.
따라서 의사코드의 (!) 이 '와' 와 '또는' 기능을 작동합니까 다음과 같습니다.
<! - 언어: > 없음 -;
def and(expr1, expr2):
left = evaluate(expr1)
if bool(left):
return evaluate(expr2)
else:
return left
def or(expr1, expr2):
left = evaluate(expr1)
if bool(left):
return left
else:
return evaluate(expr2)
이것이 의사코드의 파이썬 코드를 없습니다. Python 에서 '와' 또는 '또는' 라는 기능이 있기 때문에 여러_키워드 생성할 수 없습니다. 또한, evaluate" " 사용해서는 안 됩니다. 또는 "만약 부울 (.) '.
이 방법을 사용할 수 있는 '콜' 부울 암시적입니다 사용자정의하려면 클래스뿐만 '와', '또는' 와 '' 하지는 않습니다.
이 클래스는 다시 사용할 수 있는 방법을 표시하십시오 사용자정의된 추적할 수 있는 '내가 뭔가 인쇄하십시오 무슨일인거죠:
class Test(object):
def __init__(self, value):
self.value = value
def __bool__(self):
print('__bool__ called on {!r}'.format(self))
return bool(self.value)
__nonzero__ = __bool__ # Python 2 compatibility
def __repr__(self):
return "{self.__class__.__name__}({self.value})".format(self=self)
그래서 무슨 일이 있는 클래스 let& # 39 의 지켜보리니 함께 이러한 연산자:
>>> if Test(True) and Test(False):
... pass
__bool__ called on Test(True)
__bool__ called on Test(False)
>>> if Test(False) or Test(False):
... pass
__bool__ called on Test(False)
__bool__ called on Test(False)
>>> if not Test(True):
... pass
__bool__ called on Test(True)
잘 만든 경우에 유용하게 쓰일 수 있는 시퀀스일 컨테이너입니다.
참조 [4.1. 진릿값 테스트] (https://docs.python.org/library/stdtypes.html? = truth% 강조표시할 20value # 진릿값 테스트).
하지만 아마 조금 범위를 넘어서는 경우 원래 질문은 # 39, re 다루는 you& 누마피 어레이나 하위 클래스 (판다 시리즈이거나 다테프럼스 같은) 그런 다음 암시적입니다 부울 '콜' '이' 바루어로 띄게 방침이다.
>>> import numpy as np
>>> arr = np.array([1,2,3])
>>> bool(arr)
ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()
>>> arr and arr
ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()
>>> import pandas as pd
>>> s = pd.Series([1,2,3])
>>> bool(s)
ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().
>>> s and s
ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().
이 경우 논리적, 누마피) 에서 수행하는 함수를 사용할 수 있습니다 충족되었으며 요소점 와이즈 '와' (또는 '또는'):
>>> np.logical_and(np.array([False,False,True,True]), np.array([True, False, True, False]))
array([False, False, True, False])
>>> np.logical_or(np.array([False,False,True,True]), np.array([True, False, True, False]))
array([ True, False, True, True])
>>> np.array([False,False,True,True]) & np.array([True, False, True, False])
array([False, False, True, False])
>>> np.array([False,False,True,True]) | np.array([True, False, True, False])
array([ True, False, True, True])
< sup> < sup>;;; (1)
부울 '에 있는' 는 'True' 또는 '거짓' isn& 호출하십시오 피연산자로 반환되기를 완전히 # 39, t correct. # 39 의 첫 번째 피연산자 it& 그냥 # 39, s '에서' bool it& 부울입니다 반품해야 하는 방법:
class Test(object):
def __init__(self, value):
self.value = value
def __bool__(self):
return self.value
__nonzero__ = __bool__ # Python 2 compatibility
def __repr__(self):
return "{self.__class__.__name__}({self.value})".format(self=self)
>>> x = Test(10) and Test(10)
TypeError: __bool__ should return bool, returned int
>>> x1 = Test(True) and Test(10)
>>> x2 = Test(False) and Test(10)
>>> x1
Test(10)
>>> x2
Test(False)
마찬가지로 '또는' 를 중심으로 한 것이 아니라 다른 길로.
>>> Test(True) or Test(10)
Test(True)
>>> Test(False) or Test(10)
Test(10)
그러나 이를 사용할 경우 "만약 '선언문' 에서 '또' 콜 '부울 암시적으로 경우 결과에 대한. 이러한 점 때문에 더 적합하지 않을 수 있음 당신꺼에요.
def AND(a,b):
return (a and b) #using and operator
def OR(a,b):
return (a or b) #using or operator
이제 그들을 호출하십시오 시도하시겠습니까.
print AND(False, False)
print OR(True, False)
False
True
아마도 가장 잘 작동하고 있지 않은 이 일이 아니지만, 이 코드의 -
def front_back(a, b):
if len(a) % 2 == 0 and len(b) % 2 == 0:
print a[:(len(a)/2)] + b[:(len(b)/2)] + a[(len(a)/2):] + b[(len(b)/2):]
elif len(a) % 2 == 1 and len(b) % 2 == 0:
print a[:(len(a)/2)+1] + b[:(len(b)/2)] + a[(len(a)/2)+1:] + b[(len(b)/2):]
elif len(a) % 2 == 0 and len(b) % 2 == 1:
print a[:(len(a)/2)] + b[:(len(b)/2)+1] + a[(len(a)/2):] + b[(len(b)/2)+1:]
else :
print a[:(len(a)/2)+1] + b[:(len(b)/2)+1] + a[(len(a)/2)+1:] + b[(len(b)/2)+1:]
사용하는 and" "; 의 조건부. 내가 있는 이 주피터 가져올 때 자주 사용하는 노트북:
def find_local_py_scripts():
import os # does not cost if already imported
for entry in os.scandir('.'):
# find files ending with .py
if entry.is_file() and entry.name.endswith(".py") :
print("- ", entry.name)
find_local_py_scripts()
- googlenet_custom_layers.py
- GoogLeNet_Inception_v1.py
하나의 ',' 아닌 '더블' & &,) 는 & 크지 않거나 # 39, & # 39 위) 로, and& 제안됩니다 오토메이티드 사용할 수 있습니다. 난 또 이렇게 com/downloads/global/corporate/iar/esg_prosupport. 판다
cities['Is wide and has saint name'] = (cities['Population'] > 1000000)
& cities['City name'].apply(lambda name: name.startswith('San'))
만약 우리가 " 재장착합니다 & ";; # 39;;;, 이를 통해 " and" won& 빗나갔다.
아마 & 함께. 대신 더 빠르고 만테인 레이디빌레티 %
even/odd 다른 테스트
x 는 심지어? x = 0 2%
x 는 홀수입니다? 2% 아니라 x = 0
아마 더 함께 선택해제합니다 1 비트 and
x 는 홀수입니다? x &. 1
x 는 심지어? x & 없습니다. 1 (홀수입니다 없습니다)
def front_back(a, b):
# +++your code here+++
if not len(a) & 1 and not len(b) & 1:
return a[:(len(a)/2)] + b[:(len(b)/2)] + a[(len(a)/2):] + b[(len(b)/2):]
else:
#todo! Not yet done. :P
return