私信  •  关注

Ajax1234

Ajax1234 最近创建的主题
Ajax1234 最近回复了

一个快速的解决方法可能是治疗 _tags 作为字典的字典,顶级键是子类的名称,其关联字典包含由继承的 _tag :

from collections import defaultdict
class Foo:
  _tags = defaultdict(dict)
  @classmethod
  def _tag(cls, tag_name):
    def decorator(func):
      def tmp(*args, **kwargs):
         return func(*args, **kwargs)
      cls._tags[cls.__name__][tag_name] = func.__name__ #storing tag_name under the name of the subclass
      return tmp
    return decorator

现在,在创建子类和包装函数时, _标签 将在子类名称下存储值 _标签 被称为:

class A(Foo):
  pass

class B(Foo):
  pass

@A._tag('test_a')
def a():
  pass

@B._tag('test_b')
def b():
  pass

print(dict(Foo._tags))

输出:

{'A': {'test_a': 'a'}, 'B': {'test_b': 'b'}}
4 年前
回复了 Ajax1234 创建的主题 » 用Python创建字典[duplicate]

你可以用 zip 具有 dict :

a = ['RA CROXE-14156', 'RA CROXE-14084', ]
b = ['CR','ENGINEER_NAME','DESCRIPTION','BINARIES']
c = ['John', 'Mark']
d = ['M4 Hiding Emergency Group from mgr menu', 'M4-NRT: SQLCODE_-11300', ]
e = ['TEL', 'mao.SYM']
result = [dict(zip(b, i)) for i in zip(a, c, d, e)]

输出:

[{'CR': 'RA CROXE-14156', 'ENGINEER_NAME': 'John', 'DESCRIPTION': 'M4 Hiding Emergency Group from mgr menu', 'BINARIES': 'TEL'}, {'CR': 'RA CROXE-14084', 'ENGINEER_NAME': 'Mark', 'DESCRIPTION': 'M4-NRT: SQLCODE_-11300', 'BINARIES': 'mao.SYM'}]

不带导入的基本递归解决方案:

x = ['a', 'b', 'c']
y = [1, 2, 3]
def groups(d, c=[]):
  if len(c) == len(x):
    yield list(zip(c, y))
  else:
    for i in d:
       yield from groups(d, c+[i])

print(list(groups(x)))

输出:

[[('a', 1), ('a', 2), ('a', 3)], [('a', 1), ('a', 2), ('b', 3)], [('a', 1), ('a', 2), ('c', 3)], [('a', 1), ('b', 2), ('a', 3)], [('a', 1), ('b', 2), ('b', 3)], [('a', 1), ('b', 2), ('c', 3)], [('a', 1), ('c', 2), ('a', 3)], [('a', 1), ('c', 2), ('b', 3)], [('a', 1), ('c', 2), ('c', 3)], [('b', 1), ('a', 2), ('a', 3)], [('b', 1), ('a', 2), ('b', 3)], [('b', 1), ('a', 2), ('c', 3)], [('b', 1), ('b', 2), ('a', 3)], [('b', 1), ('b', 2), ('b', 3)], [('b', 1), ('b', 2), ('c', 3)], [('b', 1), ('c', 2), ('a', 3)], [('b', 1), ('c', 2), ('b', 3)], [('b', 1), ('c', 2), ('c', 3)], [('c', 1), ('a', 2), ('a', 3)], [('c', 1), ('a', 2), ('b', 3)], [('c', 1), ('a', 2), ('c', 3)], [('c', 1), ('b', 2), ('a', 3)], [('c', 1), ('b', 2), ('b', 3)], [('c', 1), ('b', 2), ('c', 3)], [('c', 1), ('c', 2), ('a', 3)], [('c', 1), ('c', 2), ('b', 3)], [('c', 1), ('c', 2), ('c', 3)]]
4 年前
回复了 Ajax1234 创建的主题 » 如何在python中创建新列表

你可以用 itertools.groupby

from itertools import groupby
matrixlist = [['Matrix', '1'], ['1', '4', '6'], ['5', '2', '9'], ['Matrix', '2'], ['2', '6'], ['1', '3'], ['8', '6'], ['Matrix', '3'], ['5', '6', '7', '9'], ['1', '4', '2', '3'], ['8', '7', '3', '5'], ['9', '4', '5', '3'], ['Matrix', '4'], ['7', '8'], ['4', '6'], ['2', '3']]
result = [list(b) for a, b in groupby(matrixlist, key=lambda x:x[0] == 'Matrix') if not a]

输出:

[[['1', '4', '6'], ['5', '2', '9']], 
 [['2', '6'], ['1', '3'], ['8', '6']], 
 [['5', '6', '7', '9'], ['1', '4', '2', '3'], ['8', '7', '3', '5'], ['9', '4', '5', '3']], 
 [['7', '8'], ['4', '6'], ['2', '3']]]
4 年前
回复了 Ajax1234 创建的主题 » Python:比较字典中键之间的值重叠

你可以用 collections.defaultdict :

import collections
d = {'a': [['1', '2', 'A', 'cat'], ['1', '3', 'A', 'dog']], 'b': [['1', '2', 'A', 'cat'], ['1', '3', 'A', 'dog']], 'c': [['1', '2', 'A', 'cat'], ['2', '2', 'A', 'snake'], ['2', '2', 'A', 'bird']]}
new_d = collections.defaultdict(list)
for a, b in d.items():
  for i in b:
     new_d[tuple(i)].append(a)


new_r = collections.defaultdict(list)
for a, b in new_d.items():
   new_r['/'.join(b)].append(list(a))

new_result = {a:b[0] if len(b) == 1 else b for a, b in new_r.items()}

{'a/b/c': ['1', '2', 'A', 'cat'], 'a/b': ['1', '3', 'A', 'dog'], 'c': [['2', '2', 'A', 'snake'], ['2', '2', 'A', 'bird']]}

ops = {'+':lambda x, y:x+y, '-':lambda x, y:x-y}
def _eval(d):
   return d[0] if len(d) == 1 else _eval([ops[d[1]](d[0], d[2]), *d[3:]])

def combos(vals, l, c = []):
  if not vals:
     yield c
  else:
     for i in ['+', '-']:
        if len(c) < l-1 or _eval([*c, i, vals[0]]) > 0:
           yield from combos(vals[1:], l, c+[i, vals[0]])


print(list(combos([1, 2, 3, 4, 5], 5, [1])))

输出:

[[1, '+', 1, '+', 2, '+', 3, '+', 4, '+', 5], 
 [1, '+', 1, '+', 2, '+', 3, '+', 4, '-', 5], 
 [1, '+', 1, '+', 2, '+', 3, '-', 4, '+', 5], 
 [1, '+', 1, '+', 2, '-', 3, '+', 4, '+', 5], 
 [1, '+', 1, '-', 2, '+', 3, '+', 4, '+', 5], 
 [1, '+', 1, '-', 2, '+', 3, '+', 4, '-', 5], 
 [1, '-', 1, '+', 2, '+', 3, '+', 4, '+', 5], 
 [1, '-', 1, '+', 2, '+', 3, '+', 4, '-', 5], 
 [1, '-', 1, '+', 2, '+', 3, '-', 4, '+', 5], 
 [1, '-', 1, '-', 2, '+', 3, '+', 4, '+', 5]]
4 年前
回复了 Ajax1234 创建的主题 » 如何在Python3中列出字符串中的字符?

你可以用 re.sub 并提供与要删除的内容完全匹配的模式:

import re
result = re.sub('[^a-zA-Z0-9]', '', '_abcd!?123')

输出:

'abcd123'
4 年前
回复了 Ajax1234 创建的主题 » python-嵌套列表结构中的聚合数据

你可以用 collections.defaultdict :

import collections
in_data = [[['name', 'name_1'], ['item_B', '2'], ['item_C', '3'], ['item_D', '4']], [['Skill', 'name_2'], ['item_B', '5'], ['item_A', '2']], [['Skill', 'name_3'], ['item_B', '6'], ['item_C', '7']]]
d = [list(zip(['name', *b[0][1:]], i)) for b in in_data for i in b[1:]]
new_d = collections.defaultdict(dict)
for i in d:
   new_d[dict(i)['name']][i[-1][0]] = i[-1][-1]

all_names = list({i for b in new_d.values() for i in b})[::-1]
result = [['name', *all_names], *[[a, *[b.get(k, '-') for k in all_names]] for a, b in new_d.items()]]

输出:

[['name', 'name_1', 'name_2', 'name_3'], 
 ['item_B', '2', '5', '6'], 
 ['item_C', '3', '-', '7'], 
 ['item_D', '4', '-', '-'], 
 ['item_A', '-', '2', '-']]
5 年前
回复了 Ajax1234 创建的主题 » 基于python中两个短序列的过滤行

您可以将ID按顺序分组,然后利用 re.findall :

import re
data = [i.strip('\n') for i in open('filename.txt')]
new_data = [[data[i], data[i+1]] for i in range(0, len(data), 2)]
final_result = [[a, b] for a, b in new_data if re.findall('AATAAA\w{2,}GGAC', b)]

输出:

[['>chr16:134222-134283', 'AGCTGGAAGCAGCGTGAATAAAACAGAATGGCCGGGACCTTAAAGGCTTTGCTTGGCCTGG']]
4 年前
回复了 Ajax1234 创建的主题 » 从列表组合生成python字典

你可以使用 itertools.product :

import itertools
atr = ['a','b','c']
m = ['h','i','j']
func = ['x','y','z']
prod = list(itertools.product(func, m))
result = {i:prod for i in atr}

输出:

{'a': [('x', 'h'), ('x', 'i'), ('x', 'j'), ('y', 'h'), ('y', 'i'), ('y', 'j'), ('z', 'h'), ('z', 'i'), ('z', 'j')], 'b': [('x', 'h'), ('x', 'i'), ('x', 'j'), ('y', 'h'), ('y', 'i'), ('y', 'j'), ('z', 'h'), ('z', 'i'), ('z', 'j')], 'c': [('x', 'h'), ('x', 'i'), ('x', 'j'), ('y', 'h'), ('y', 'i'), ('y', 'j'), ('z', 'h'), ('z', 'i'), ('z', 'j')]}
5 年前
回复了 Ajax1234 创建的主题 » 使用python flask和jquery删除sqlite数据库中的行

而不是 form ,只需创建 input 字段。当选择按钮时, ajax 可以做一个 GET 请求:

from flask import jsonify

@app.route("/")
@app.route('/delete')
def delete():
  con = sqlite3.connect('ships.db')
  cur = con.cursor()
  cur.execute('DELETE FROM `liners` WHERE liner_ip = "' +  request.args.get('id')+ '"')
  cur.commit()
  con.close()
  return flask.jsonify({'success':"True"})

然后,在 html :

<html>
  <head>
       <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
  </head>
    <body>
      <div class='wrapper'> <!--Need wrapper for anchoring button click -->
        <input type="hidden" name="id" class='input_row' value="{{row['liner_ip']}}">
        <button class='delete_row'>DELETE</button>
      </div>
    </body>
    <script>
      $(document).ready(function(){
        $('.wrapper').on('click', '.delete_row', function(){
          var val = $('.input_row').val();
          $.ajax({
            url: "/suggestions",
            type: "get",
            data: {id: val},
            success: function(response) {
              $('.input_row').val('');
            },

          });
        });
      });
    </script>
</html>
5 年前
回复了 Ajax1234 创建的主题 » 用python解构dict和objects

您可以实现 __iter__ 启用解包的方法:

class User:
  def __init__(self, **data):
    self.__dict__ = data
  def __iter__(self):
    yield from [getattr(self, i) for i in ('id', 'email', 'gender', 'username')]

current_user = User(**currentUser)
id, email, gender, username = current_user
print([id, email, gender, username])

输出:

[24, 'example@example.com', 'M', 'johndoe']

编辑:python2溶液:

class User:
  def __init__(self, **data):
    self.__dict__ = data
  def __iter__(self):
    for i in ('id', 'email', 'gender', 'username'):
      yield getattr(self, i)

编辑2:

获取选定属性:

class User:
  def __init__(self, **data):
     self.__dict__ = data
  def __getattr__(self, _vals):
     yield from [getattr(self, i) for i in _vals.split('_')]

current_user = User(**currentUser)
id, email, gender, username = current_user.id_email_gender_username
id, gender = current_user.id_gender

您可以使用列表理解:

myList = ['1-1-1', '1-1-2', '1-2-1', '1-2-2', '1-3-1']
_split = list(map(lambda x:x.split('-'), myList))
s, s2 = {a for a, *_ in _split}, {f'{a}-{b}' for a, b, _ in _split}
new_data = {i:{c:[h for h in myList if h.startswith(c)] for c in s2 if c[0] == i} for i in s}

输出:

{'1': {'1-2': ['1-2-1', '1-2-2'], '1-1': ['1-1-1', '1-1-2'], '1-3': ['1-3-1']}
5 年前
回复了 Ajax1234 创建的主题 » 如何在python中删除字符串中的某些空格?[副本]

你可以用 re.sub :

import re
print(re.sub('(?<=\n)\s+\n', '', content))

输出:

"subject: Exercise Feedback Form
persona_id: bresse
Q1: Yes
Q1 comments: Yes everything was found A1
Q2: No
Q2 comments: No forgot to email me A2
Q3: Yes
Q3 comments: All was good A3
Q4: No
Q4 comments: It was terrible A4
Q5_comments: Get Alex to make it better
subject: Issue With App
persona_id: bresse
comments: Facebook does not work comments feedback"
5 年前
回复了 Ajax1234 创建的主题 » 使用python从一系列日期中检查项目列表

您可以使用 datetime 模块:

import datetime
def to_datetime(d):
 day, month, year = map(int, d.split('/'))
 return datetime.datetime(year, month, day, 0, 0, 0)

a = '01/08/2017'
b = '28/08/2017'
_a = to_datetime(a)
_b = to_datetime(b)
c = ['01/08/2017', '20/08/2017', '21/08/2017', '22/08/2017', '23/08/2017', '24/08/2017', '25/08/2017', '26/08/2017', '27/08/2017', '28/08/2017']
for i in c:
  if _a <= to_datetime(i) <= _b:
    print(i)

输出:

01/08/2017
20/08/2017
21/08/2017
22/08/2017
23/08/2017
24/08/2017
25/08/2017
26/08/2017
27/08/2017
28/08/2017