我将 csv 文件读入名为rr. 角色栏被视为因素,这很好。
我是否正确理解这些levels只是unique列的值?IE
levels(rr$col) == unique(rr$col)
Run Code Online (Sandbox Code Playgroud)
然后我想去掉前导和尾随空格。(我不知道 read 中的 strip.WHITESPACE 选项)所以我做了
rr$col = str_trim(rr$col).
Run Code Online (Sandbox Code Playgroud)
现在rr$col不再是一个因素了。所以我做了
rr$col = as.factor(rr$col)
Run Code Online (Sandbox Code Playgroud)
但我现在发现它levels(rr$col)缺少一些独特的价值观!为什么?
这里的代码适合我.但我是Python的新手,想知道并了解是否有更优雅或pythonic的方式来完成这项工作.
有一个包含两元素元组的列表.我想加入相等的列表元素并将相等元素的数量存储为第三个元组元素(在其他两元组元素前面的第一个).
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
org = [ ( 12, 4 ),
( 8, 4 ),
( 12, 8 ),
( 12, 8 ) ]
# should result in
# [ ( 1, 12, 4 ),
# ( 1, 8, 4 ),
# ( 2, 12, 8 ) ]
def count_element(count_in, e):
"""
How often does 'e' appear in 'count_in'.
"""
count = 0
for x in count_in:
if x == e:
count += 1
return …Run Code Online (Sandbox Code Playgroud) 与列表中给出的数字相比,您将如何找到最接近的数字?
这是我迄今为止尝试过的,但没有成功:
setted_list = [2, 9, 6, 20, 15]
value_chosen = 17
while True:
final_value = setted_list[0]
if setted_list[1] - value_chosen < setted_list[0] - value_chosen:
final_value = setted_list[1]
if setted_list[2] - value_chosen < setted_list[1] - value_chosen:
final_value = setted_list[2]
if setted_list[3] - value_chosen < setted_list[2] - value_chosen:
final_value = setted_list[3]
if setted_list[4] - value_chosen < setted_list[3] - value_chosen:
final_value = setted_list[4]
print(final_value)
Run Code Online (Sandbox Code Playgroud)
我的输出始终是setted_list[2]. 我的算法哪里出错了?
我想通过将文本(行中列的)加粗或不加粗来显示行的已读或未读状态。
行的状态(或模型中的数据)可以是模型的一部分或其他地方。在这一点上,我很灵活。
如何根据基础(动态)数据将特定单元格的文本设为粗体,在本例中为值1?
#!/usr/bin/env python3
import gi
gi.require_version('Gtk', '3.0')
from gi.repository import Gtk
class View(Gtk.TreeView):
def __init__(self, model):
Gtk.TreeView.__init__(self, model)
col = Gtk.TreeViewColumn('Text',
Gtk.CellRendererText(),
text=0)
self.append_column(col)
# bold text
# Gtk.CellRendererText(weight_set=True, weight=700),
class Model(Gtk.ListStore):
def __init__(self):
Gtk.ListStore.__init__(self, str, int)
self.append(['foo 1', 0])
self.append(['foo 2', 1]) # bold
self.append(['foo 3', 0])
self.append(['foo 4', 0])
self.append(['foo 5', 1]) # bold
class Window(Gtk.Window):
def __init__(self):
Gtk.Window.__init__(self)
self.set_default_size(100, 200)
# model & view
self.model …Run Code Online (Sandbox Code Playgroud) 我是 urwid 的新手,认为我误解了一些东西。我不明白为什么这不起作用。而且我不明白错误消息。
#!/usr/bin/env python3
import urwid
def show_or_exit(key):
if key in ('q', 'Q'):
raise urwid.ExitMainLoop()
txt.set_text(repr(key))
txt = urwid.Text('FooBar')
fil = urwid.Filler(txt, valign='middle', height=('relative', 70))
box = urwid.LineBox(fil)
pad = urwid.Padding(box, align='center', width=('relative', 85))
loop = urwid.MainLoop(pad, unhandled_input=show_or_exit)
loop.run()
Run Code Online (Sandbox Code Playgroud) 问题是我的解决方案是否是一种使用来自另一个线程的数据更新 Tkinter-GUI 的保存和 pythonic 方式?是Lock必需的吗?或者怎么能在Queue这里提供帮助?此示例运行良好,但原始应用程序需要处理复杂得多的数据。
请专注于AsyncioThread.create_dummy_data()最小的工作示例。该示例有两个线程。一个运行Tkinter -mainloop,第二个线程运行asyncio -loop。异步循环模拟获取一些数据并tkinter.Label用这些数据刷新一些数据。
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# restrict to Python3.5 or higher because of asyncio syntax
# based on </sf/answers/3354408991/>
from tkinter import *
import asyncio
import threading
import random
class AsyncioThread(threading.Thread):
def __init__(self, asyncio_loop, theWindow):
self.asyncio_loop = asyncio_loop
self.theWindow = theWindow
self.maxData = len(theWindow.varData)
threading.Thread.__init__(self)
def run(self):
self.asyncio_loop.run_until_complete(self.do_data())
async def do_data(self):
""" Creating and starting 'maxData' asyncio-tasks. """ …Run Code Online (Sandbox Code Playgroud) python asynchronous tkinter python-multithreading python-asyncio
这个问题一般与观察者模式无关。它专注于在该模式中使用装饰器。该问题基于类似问题的答案。
#!/usr/bin/env python3
class Observable:
"""
The object that need to be observed. Alternative names are 'Subject'.
In the most cases it is a data object.
"""
def __init__(self):
self._observers = []
def register_observer(self, callback):
self._observers.append(callback)
return callback
def _broadcast_observers(self, *args, **kwargs):
for callback in self._observers:
callback(*args, **kwargs)
class TheData(Observable):
"""
Example of a data class just for demonstration.
"""
def __init__(self, data):
Observable.__init__(self)
self._data = data
@property
def data(self):
return self._data
@data.setter
def data(self, data):
self._data = …Run Code Online (Sandbox Code Playgroud) x' = f(x,y,t)
y' = g(x,y,t)
Run Code Online (Sandbox Code Playgroud)
初始条件已给出为 x0 和 y0 以及 t0。求 t0 到 a 范围内的解图。
我曾尝试对非耦合方程执行此操作,但似乎也存在问题。我必须使用这个函数来解决这个问题,所以其他函数不是选项。
from numpy import *
from matplotlib import pyplot as plt
def f(t,x):
return -x
import scipy
from scipy import integrate as inte
solution = inte.RK45(f, 0 , [1] , 10 ,1, 0.001, e**-6)
print (solution)
Run Code Online (Sandbox Code Playgroud)
我希望输出是所有值的数组。
但这<scipy.integrate._ivp.rk.RK45 at 0x1988ba806d8>就是我得到的。
PandasDataFrame.to_csv方法的选项quoting=csv.QUOTE_MINIMAL似乎不起作用。
我有以下输入制表符分隔的数据,在下面的示例中 -> 表示制表符和 。表示空格字符。
Jhon->35->123.Vroom.St->01120
使用DataFrame.to_csv选项 quoting=csv.QUOTE_MINIMAL` 之后,我期待以下输出。
Jhon 35 "123 Vroom St" 01120
这意味着仅引用分隔数据中有空格的地址值,如果没有空格则不引用。
df.to_csv(file,
sep='\t',
header=False,
index=False,
quoting=csv.QUOTE_MINIMAL)
Run Code Online (Sandbox Code Playgroud)
但是,我得到以下输出。地址上没有报价。
Jhon 35 123 Vroom St 01120
使用选项 quoting=csv.QUOTE_ALL` 让我低于我不想要的。
"Jhon" "35" "123 Vroom St" "01120"
有人可以帮我看看这里出了什么问题吗?
谢谢。
我经常这样做:
>>> x = [1,2,3,4,5]
>>> s = ''
>>> for i in x:
... s = '{}, {}'.format(s, i)
...
>>> s
', 1, 2, 3, 4, 5'
>>> if s[0] == ',':
... s = s[2:]
...
>>> s
'1, 2, 3, 4, 5'
Run Code Online (Sandbox Code Playgroud)
我经常认为有更多的pythonic-3方法可以做到这一点.任何的想法?
这段代码使用List Comprehension什么是无效的.
l = ['banana', 'apple', 'linux', 'pie', 'banana', 'win', 'apple', 'banana']
d = {e:l.count(e) for e in l}
d
{'pie': 1, 'linux': 1, 'banana': 3, 'apple': 2, 'win': 1}
Run Code Online (Sandbox Code Playgroud)
什么是更好的方法来计算这个未排序列表中的字符串而不会丢失字符串与其计数之间的连接?
我是 python 的新手,据我所知,python 没有某种“数学”舍入。或者说有吗?我有一个温度数组,例如:
temp = [-20.5, -21.5, -22.5, -23.5, 10.5, 11.5, 12.5, 13.5]
Run Code Online (Sandbox Code Playgroud)
我无法以数学方式将值四舍五入的方法改进为:
>> [-21, -21, -22, -22, -22, -24, -23, -23, -23, -23, -24, ...]
Run Code Online (Sandbox Code Playgroud)
因此,-20.5 四舍五入到 -21、-21.5 四舍五入到 -22、-23.5 四舍五入到 -24、10.5 四舍五入到 11、11.5 四舍五入到 12、12.5 四舍五入到 13。在我的情况下,数学准确性很重要。
对我来说最好的选择是使用像 numpy.around() 这样的函数,因为它对所有值进行四舍五入,而不是一一舍入(我想,它更快)。有这样的功能,或者有这样的方式吗?
我得到的结果:
np.around(temp, decimals=0)
>>[-20. -22. -22. -24. 10. 12. 12. 14.]
np.rint(temp)
>>[-20. -22. -22. -24. 10. 12. 12. 14.]
np.round(temp)
>>[-20. -22. -22. -24. 10. 12. 12. 14.]
np.trunc(temp)
>>[-20. -21. -22. -23. 10. 11. …Run Code Online (Sandbox Code Playgroud) 我喜欢在 Python 中使用any()and 。all()但有时我需要一个one().
我想知道列表中是否只有一个True值或条件是.
目前我用这样一个嵌套的丑陋来做到这一点if。
# In real world there could be more then just two elements
istrue = [True, False]
isfalse = [True, 'foobar']
isfalse2 = [False, False]
def one(values):
if values[0] and values[1]:
return False
if not values[0] and not values[1]:
return False
return True
one(istrue) # True
one(isfalse) # False
one(isfalse2) # False
Run Code Online (Sandbox Code Playgroud)
我认为有一种更Pythonic的方式,不是吗?