我刚刚发现python中存在一个Enum基类,我试图想象它对我有用.
假设我定义了一个红绿灯状态:
from enum import Enum, auto
class Signal(Enum):
red = auto()
green = auto()
orange = auto()
Run Code Online (Sandbox Code Playgroud)
假设我从程序中的某个子系统接收信息,例如以表示颜色名称的字符串的形式brain_detected_colour = "red".
如何将此字符串与我的红绿灯信号进行比较?
显然,brain_detected_colour is Signal.red是False因为Signal.red不是一个字符串.
Signal(brain_detected_colour) is Signal.red失败了ValueError: 'red' is not a valid Signal.
我是 Docker 的初学者,我正在尝试分两个阶段构建映像,如下所述:https : //docs.docker.com/develop/develop-images/multistage-build/
您可以有选择地将工件从一个阶段复制到另一个阶段
查看那里给出的示例,我认为可以在第一阶段构建一些文件,然后将它们提供给下一个阶段:
FROM golang:1.7.3 AS builder
WORKDIR /go/src/github.com/alexellis/href-counter/
RUN go get -d -v golang.org/x/net/html
COPY app.go .
RUN CGO_ENABLED=0 GOOS=linux go build -a -installsuffix cgo -o app .
FROM alpine:latest
RUN apk --no-cache add ca-certificates
WORKDIR /root/
COPY --from=builder /go/src/github.com/alexellis/href-counter/app .
CMD ["./app"]
Run Code Online (Sandbox Code Playgroud)
(示例取自上述链接页面)
那不是应该做的COPY app.go .和COPY --from=builder /go/src/github.com/alexellis/href-counter/app .应该做的吗?
我可能对正在发生的事情有一个完全的误解,因为当我尝试做类似的事情时(见下文),似乎COPY第一阶段的命令无法看到刚刚构建的文件(我可以确认它们实际上是使用一个RUN ls步骤构建的,但是我得到了一个lstat <the file>: no such file or directory错误)。
事实上,我可以收集到的大多数其他信息COPY(除了上面链接中的示例),而是表明这COPY实际上是为了从 …
我正在尝试在我的 python 代码上输入一些内容,但出现以下 mypy 错误:“不支持索引分配的目标”
在一个简化的例子中,它相当于以下代码:
from pathlib import Path
from typing import (Literal, Mapping,
Optional, Union)
STRAND = Literal["+", "-"]
PATH = Union[str, Path]
fastq_files: Mapping[STRAND, Optional[PATH]] = { # simultaneous annotation and assignment
"+": None,
"-": None}
reads_dir = Path("/tmp")
fastq_files["+"] = reads_dir.joinpath( # mypy error
"plus.fastq.gz")
fastq_files["-"] = reads_dir.joinpath( # mypy error
"minus.fastq.gz")
Run Code Online (Sandbox Code Playgroud)
用字典值中的Nonea替换时会出现错误Path。
既然是这样,为什么应该是 type 的Optional[PATH]值不能被 type 的值替换?我会认为 a与 兼容,而后者又与.PathPATHUnion[str, Path]PathUnion[str, Path]Optional[Union[str, Path]]
为什么当我在赋值之前注释 …
我有以下pandas数据帧df(实际上只是更大的数据帧的最后一行):
count
gene
WBGene00236788 56
WBGene00236807 3
WBGene00249816 12
WBGene00249825 20
WBGene00255543 6
__no_feature 11697881
__ambiguous 1353
__too_low_aQual 0
__not_aligned 0
__alignment_not_unique 0
Run Code Online (Sandbox Code Playgroud)
我可以使用filter's regex选项只获得以两个下划线开头的行:
df.filter(regex="^__", axis=0)
Run Code Online (Sandbox Code Playgroud)
这将返回以下内容:
count
gene
__no_feature 11697881
__ambiguous 1353
__too_low_aQual 0
__not_aligned 0
__alignment_not_unique 0
Run Code Online (Sandbox Code Playgroud)
实际上,我想要的是补充:只有那些不以两个下划线开头的行.
我可以用另一个正则表达式做到:df.filter(regex="^[^_][^_]", axis=0).
有没有办法更简单地指定我想要初始正则表达式的倒数?
这种基于正则表达式的过滤是否有效?
df.filter(regex="(?!^__)", axis=0)并且df.filter(regex="^\w+", axis=0)都返回所有行.
根据re模块文档,\w特殊字符实际上包括下划线,它解释了第二个表达式的行为.
我想第一个不起作用,因为它(?!...)适用于模式之后的内容.这里,"^"应该放在外面,如下面提出的解决方案:
df.filter(regex="^(?!__).*?$", axis=0) 作品.
那样做df.filter(regex="^(?!__)", axis=0).
我编写了一个使用的小python脚本multiprocessing(参见/sf/answers/2931299801/).它在我测试它时起作用:
$ ./forkiter.py
0
1
2
3
4
sum of x+1: 15
sum of 2*x: 20
sum of x*x: 30
Run Code Online (Sandbox Code Playgroud)
但是当我尝试对其进行分析时cProfile,我会得到以下结果:
$ python3.6 -m cProfile -o forkiter.prof ./forkiter.py
0
1
2
3
4
Traceback (most recent call last):
File "/home/bli/lib/python3.6/runpy.py", line 193, in _run_module_as_main
"__main__", mod_spec)
File "/home/bli/lib/python3.6/runpy.py", line 85, in _run_code
exec(code, run_globals)
File "/home/bli/lib/python3.6/cProfile.py", line 160, in <module>
main()
File "/home/bli/lib/python3.6/cProfile.py", line 153, in main
runctx(code, globs, None, options.outfile, options.sort)
File "/home/bli/lib/python3.6/cProfile.py", …Run Code Online (Sandbox Code Playgroud) 以下是一些测试itertools.tee:
li = [x for x in range(10)]
ite = iter(li)
==================================================
it = itertools.tee(ite, 5)
>>> type(ite)
<type 'listiterator'>
>>> type(it)
<type 'tuple'>
>>> type(it[0])
<type 'itertools.tee'>
>>>
>>> list(ite)
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> list(it[0]) # here I got nothing after 'list(ite)', why?
[]
>>> list(it[1])
[]
====================play again===================
>>> ite = iter(li)
it = itertools.tee(ite, 5)
>>> list(it[1])
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> …Run Code Online (Sandbox Code Playgroud) 我注意到我的备份rsync脚本花了很多时间从.snakemake/metadata文件夹中复制具有随机名称的内容。
这些文件是用来做什么的?
我可以在完成蛇形运行之后安全地擦除它们吗,或者它们是蛇形正确执行下一次运行所必需的吗?
更一般而言,是否有一些有关蛇形.snakemake文件夹中创建的文件的文档?
在以下ipython3会话中,我读取了格式不同的表,并对其中一列中的值求和:
In [278]: F = pd.read_table("../RNA_Seq_analyses/mapping_worm_number_tests/hisat2/mapped_C_elegans/feature_count/W100_1_on_C_elegans/protein_coding_fwd_counts.txt", skip
...: rows=2, usecols=[6]).sum()
In [279]: S = pd.read_table("../RNA_Seq_analyses/mapping_worm_number_tests/hisat2/mapped_C_elegans/intersect_count/W100_1_on_C_elegans/protein_coding_fwd_counts.txt", us
...: ecols=[6], header=None).sum()
In [280]: S
Out[280]:
6 3551266
dtype: int64
In [281]: F
Out[281]:
72 3164181
dtype: int64
In [282]: type(F)
Out[282]: pandas.core.series.Series
In [283]: type(S)
Out[283]: pandas.core.series.Series
In [284]: F[0]
Out[284]: 3164181
In [285]: S[0]
---------------------------------------------------------------------------
KeyError Traceback (most recent call last)
<ipython-input-285-5a4339994a41> in <module>()
----> 1 S[0]
/home/bli/.local/lib/python3.6/site-packages/pandas/core/series.py in __getitem__(self, key)
601 result = self.index.get_value(self, key)
602
--> 603 if not …Run Code Online (Sandbox Code Playgroud) 考虑以下脚本,我在其中测试两种方法,对通过以下方式获得的生成器执行某些计算itertools.tee:
#!/usr/bin/env python3
from sys import argv
from itertools import tee
from multiprocessing import Process
def my_generator():
for i in range(5):
print(i)
yield i
def double(x):
return 2 * x
def compute_double_sum(iterable):
s = sum(map(double, iterable))
print(s)
def square(x):
return x * x
def compute_square_sum(iterable):
s = sum(map(square, iterable))
print(s)
g1, g2 = tee(my_generator(), 2)
try:
processing_type = argv[1]
except IndexError:
processing_type = "no_multi"
if processing_type == "multi":
p1 = Process(target=compute_double_sum, args=(g1,))
p2 = Process(target=compute_square_sum, args=(g2,))
print("p1 starts") …Run Code Online (Sandbox Code Playgroud) 使用以下小数据集:
bill = [34,108,64,88,99,51]
tip = [5,17,11,8,14,5]
Run Code Online (Sandbox Code Playgroud)
我计算了最佳拟合回归线(手动).
yi = 0.1462*x - 0.8188 #yi = slope(x) + intercept
Run Code Online (Sandbox Code Playgroud)
我使用Matplotlib绘制了原始数据,如下所示:
scatter(bill,tip, color="black")
plt.xlim(20,120) #set ranges
plt.ylim(4,18)
#plot centroid point (mean of each variable (74,10))
line1 = plt.plot([74, 74],[0,10], ':', c="red")
line2 = plt.plot([0,74],[10,10],':', c="red")
plt.scatter(74,10, c="red")
#annotate the centroid point
plt.annotate('centroid (74,10)', xy=(74.1,10), xytext=(81,9),
arrowprops=dict(facecolor="black", shrink=0.01),
)
#label axes
xlabel("Bill amount ($)")
ylabel("Tip amount ($)")
#display plot
plt.show()
Run Code Online (Sandbox Code Playgroud)
我不确定如何将回归线放到情节本身上.我知道有很多内置的东西可以快速拟合和显示最合适的线条,但我这样做是为了练习.我知道我可以在点'0,0.8188'(截距)处开始该线,但我不知道如何使用斜率值来完成该线(设置线端点).
鉴于x轴上的每次增加,斜率应增加"0.1462"; 对于起点我尝试(0,0.8188)的线坐标,以及(100,14.62)终点.但是这条线并没有通过我的质心点.它错过了它.
干杯,乔恩
python ×8
pandas ×2
cprofile ×1
docker ×1
docker-copy ×1
dockerfile ×1
duplicates ×1
enums ×1
fork ×1
iterator ×1
matplotlib ×1
mypy ×1
pickle ×1
plot ×1
python-3.6 ×1
regex ×1
snakemake ×1
tee ×1
type-hinting ×1
union-types ×1