在本文中,我们将为您详细介绍如何在Python中获得两个变量的逻辑异或?的相关知识,并且为您解答关于pythonfor两个变量的疑问,此外,我们还会提供一些关于Prthon-如何在Python中获得像
在本文中,我们将为您详细介绍如何在Python中获得两个变量的逻辑异或?的相关知识,并且为您解答关于python for两个变量的疑问,此外,我们还会提供一些关于Prthon-如何在Python中获得像Cron这样的调度程序?、python - 如何在python中的一个图形中根据不同绘图的一个变量获得不同的线条颜色?、python – 对Django Q对象执行逻辑异或、Python中四种交换两个变量的值的方法的有用信息。
本文目录一览:- 如何在Python中获得两个变量的逻辑异或?(python for两个变量)
- Prthon-如何在Python中获得像Cron这样的调度程序?
- python - 如何在python中的一个图形中根据不同绘图的一个变量获得不同的线条颜色?
- python – 对Django Q对象执行逻辑异或
- Python中四种交换两个变量的值的方法
如何在Python中获得两个变量的逻辑异或?(python for两个变量)
如何在Python中获得两个变量的逻辑异或?
例如,我有两个期望是字符串的变量。我想测试其中只有一个包含True值(不是None或空字符串):
str1 = raw_input("Enter string one:")str2 = raw_input("Enter string two:")if logical_xor(str1, str2): print "ok"else: print "bad"
该^
运营商似乎是按位,并在所有对象没有定义:
>>> 1 ^ 10>>> 2 ^ 13>>> "abc" ^ ""Traceback (most recent call last): File "<stdin>", line 1, in <module>TypeError: unsupported operand type(s) for ^: ''str'' and ''str''
答案1
小编典典如果你已经将输入标准化为布尔值,则!=
为xor
。
bool(a) != bool(b)
Prthon-如何在Python中获得像Cron这样的调度程序?
我正在寻找在Python
库将提供at
和cron
一样的功能。
我很想拥有一个纯Python
解决方案,而不是依赖于安装在盒子上的工具;这样,我可以在没有cron
的机器上运行。
对于不熟悉的用户,cron
您可以根据以下表达式来安排任务:
0 2 * * 7 /usr/bin/run-backup # run the backups at 0200 on Every Sunday 0 9-17/2 * * 1-5 /usr/bin/purge-temps # run the purge temps command, every 2 hours between 9am and 5pm on Mondays to Fridays.
cron时间表达式语法不太重要,但是我希望具有这种灵活性。
如果没有任何东西可以为我提供开箱即用的功能,将不胜感激地收到任何有关构建基块做出类似建议的建议。
编辑 我对启动过程不感兴趣,只是“工作”也用Python编写-python
函数。必要时,我认为这将是一个不同的线程,但不会出现在不同的过程中。
为此,我正在寻找cron
时间表达式的可表达性,但是要使用Python
。
Cron
已经存在了很多年,但我正在尝试尽可能地便携。我不能依靠它的存在。
答案1
小编典典如果你正在寻找轻巧的结帐时间表:
import scheduleimport timedef job(): print("I''m working...")schedule.every(10).minutes.do(job)schedule.every().hour.do(job)schedule.every().day.at("10:30").do(job)while 1: schedule.run_pending() time.sleep(1)
python - 如何在python中的一个图形中根据不同绘图的一个变量获得不同的线条颜色?
这里有一些代码,在我看来,你可以很容易地适应你的问题
import numpy as np
import matplotlib.pyplot as plt
from random import randint
# generate some data
N,vmin,vmax = 12,20
rd = lambda: randint(vmin,vmax)
segments_z = [((rd(),rd()),(rd(),rd()) for _ in range(N)]
# prepare for the colorization of the lines,# first the normalization function and the colomap we want to use
norm = plt.Normalize(vmin,vmax)
cm = plt.cm.rainbow
# most important,plt.plot doesn't prepare the ScalarMappable
# that's required to draw the colorbar,so we'll do it instead
sm = plt.cm.ScalarMappable(cmap=cm,norm=norm)
# plot the segments,the segment color depends on z
for p1,p2,z in segments_z:
x,y = zip(p1,p2)
plt.plot(x,y,color=cm(norm(z)))
# draw the colorbar,note that we pass explicitly the ScalarMappable
plt.colorbar(sm)
# I'm done,I'll show the results,# you probably want to add labels to the axes and the colorbar.
plt.show()
python – 对Django Q对象执行逻辑异或
import operator from django.conf import settings from django.db import models from django.db.models import Q from django.contrib.auth.models import User,Group def query_group_lkup(group_name): return Q(user__user__groups__name__exact=group_name) class Book(models.Model): author = models.ForeignKey( User,verbose_name=_("Author"),null=False,default='',related_name="%(app_label)s_%(class)s_author",# This would have provide an exclusive OR on the selected group name for User limit_choices_to=reduce( operator.xor,map(query_group_lkup,getattr(settings,'AUTHORIZED_AUTHORS','')) )
AUTHORIZED_AUTHORS是现有组名的列表.
但这不起作用,因为Q对象不支持^运算符(仅来自docs的|和&运算符).来自stacktrace的消息(部分)如下:
File "/home/moi/.virtualenvs/venv/lib/python2.7/site-packages/django/db/models/loading.py",line 64,in _populate self.load_app(app_name,True) File "/home/moi/.virtualenvs/venv/lib/python2.7/site-packages/django/db/models/loading.py",line 88,in load_app models = import_module('.models',app_name) File "/home/moi/.virtualenvs/venv/lib/python2.7/site-packages/django/utils/importlib.py",line 35,in import_module __import__(name) File "/opt/dvpt/toto/apps/book/models.py",line 42,in <module> class Book(models.Model): File "/opt/dvpt/toto/apps/book/models.py",line 100,in Book map(query_group_lkup,'')) TypeError: unsupported operand type(s) for ^: 'Q' and 'Q'
因此,受到answer的启发,我试图为我的特定查找实现XOR.它不是很灵活,因为查找是硬编码的(我需要在query_xor的参数中使用kwargs,例如……).我最终做了这样的事情:
from django.conf import settings from django.db import models from django.db.models import Q from django.db.models.query import EmptyQuerySet from django.contrib.auth.models import User,Group def query_xor_group(names_group): """Get a XOR of the queries that match the group names in names_group.""" if not len(names_group): return EmptyQuerySet() elif len(names_group) == 1: return Q(user__user__groups__name__exact=names_group[0]) q_chain_or = Q(user__user__groups__name__exact=names_group[0]) q_chain_and = Q(user__user__groups__name__exact=names_group[0]) for name in names_group[1:]: query = Q(user__user__groups__name__exact=name) q_chain_or |= query q_chain_and &= query return q_chain_or & ~q_chain_and class Book(models.Model): author = models.ForeignKey( User,verbose_name=_("author"),# This provides an exclusive OR on the SELECT group name for User limit_choices_to=query_xor_group(getattr(settings,'')) )
它按我的意思工作,但我觉得我不是pythonic(尤其是query_xor_group方法).
这样做会有更好的(更直接的方式)吗?
基本上,我的问题可以被剥夺limit_choices_to部分,并总结为:
如何以Djangonic方式对一组django.db.models.Q对象进行按位异或?
解决方法
from django.db.models import Q class QQ: def __xor__(self,other): not_self = self.clone() not_other = other.clone() not_self.negate() not_other.negate() x = self & not_other y = not_self & other return x | y Q.__bases__ += (QQ,)
在这之后我能够在filter()调用中进行Q(…)^ Q(…).
Foobar.objects.filter(Q(blah=1) ^ Q(bar=2))
这意味着原始尝试不再抛出不受支持的操作数异常.
limit_choices_to=reduce( operator.xor,'')) )
在Python 2.7.5上测试Django 1.6.1
Python中四种交换两个变量的值的方法
Python中四种交换两个变量的值的方法
方法一:(所有语言都可以通过这种方式进行交换变量)
通过新添加中间变量的方式,交换数值.
下面通过一个demo1函数进行演示:
def demo1(a,b):
temp = a
a = b
b = temp
print(a,b)
方法二:(此方法是Python中特有的方法)
直接将a, b两个变量放到元组中,再通过元组按照index进行赋值的方式进行重新赋值给两个变量。
下面通过一个demo2函数进行演示:
def demo2(a,b):
a,b = b,a
print(a,b)
方法三:
通过简单的逻辑运算进行将两个值进行互换
下面通过一个demo3函数进行演示:
def demo3(a, b):
a = a + b
b = a - b
a = a - b
print(a, b)
方法四:
通过异或运算 将两个值互换 异或运算的原理是根据二进制中的 "1^1=0 1^0=1 0^0=0"
下面通过一个demo4函数进行演示:
def demo4(a,b):
a = a^b
b = a^b # b = (a^b)^b = a
a = a^b # a = (a^b)^a = b
print(a,b)
今天的关于如何在Python中获得两个变量的逻辑异或?和python for两个变量的分享已经结束,谢谢您的关注,如果想了解更多关于Prthon-如何在Python中获得像Cron这样的调度程序?、python - 如何在python中的一个图形中根据不同绘图的一个变量获得不同的线条颜色?、python – 对Django Q对象执行逻辑异或、Python中四种交换两个变量的值的方法的相关知识,请在本站进行查询。
本文标签: