Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/321.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 使此代码看起来更优雅_Python_Encryption - Fatal编程技术网

Python 使此代码看起来更优雅

Python 使此代码看起来更优雅,python,encryption,Python,Encryption,我对python和编程非常陌生,我做了这个,我想听听关于如何改进和使它看起来更优雅的意见,提前谢谢 我一直在学习编解码器和Udacity的课程,我学到了很多东西 import itertools #Genera coodernadas-Generate Coordinates coordinates = [[x,y] for x in range(1,6) for y in range(1,6)] #Genera alfabeto-Generate Alphabet alfa = [] f

我对python和编程非常陌生,我做了这个,我想听听关于如何改进和使它看起来更优雅的意见,提前谢谢

我一直在学习编解码器和Udacity的课程,我学到了很多东西

import itertools


#Genera coodernadas-Generate Coordinates
coordinates = [[x,y] for x in range(1,6) for y in range(1,6)]

#Genera alfabeto-Generate Alphabet
alfa = []
for i in range(97,123):
    alfa.append(chr (i))
alfa.remove("i")

#Genera diccionario de coordenadas y alfabeto - Generate dictionary and coordinates alphabet 
alfacor = {}
alfacor = dict(zip(alfa,coordinates))


#Leer Txt - Read txt
document = open("Z:\\R\\Desktop\\BIFIDO\\easy.txt")
contenido = document.read()
print (contenido)
document.close()

#Encripta fase1 - Get's coordinates of txt
encripta = []
for e in contenido:
    encripta.append(alfacor[e])

#Unir lista encripta - Merge content of encropita in a new list
merged = list(itertools.chain.from_iterable(encripta))

#Divido lista merge en partes iguales - Divide meged list to get new coordinates
B = merged[:len(merged)/2]
C = merged[len(merged)/2:]

#Unir B y C - Zip B and C to get a new list of coordinates
zipped = zip(B,C)

#Make a new list from zipped to convert from tuple to list
final_list = [list(elem) for elem in zipped]

#Convert contect of alfacor to tuples
inv_alfacor = {}
for letter, coordinate in alfacor.iteritems():
inv_alfacor[tuple(coordinate)] = letter

#Substitude coordinates of final_list from elements of inv_alfacor
encripta_f = []
for element in final_list:
    element = tuple(element)
    if element in inv_alfacor:
        encripta_f.append(inv_alfacor[element])

print "Tu palabra ",encripta_f    
  • 语句一起使用
  • 您可以在本文或中阅读更多内容

    建议的修改:

    #Leer Txt - Read txt
    with open("Z:\\R\\Desktop\\BIFIDO\\easy.txt", "r") as document:
        contenido = document.read()
        print (contenido)
    
    #Genera alfabeto-Generate Alphabet
    alfa = [chr(i) for i in xrange(97, 123) if chr(i) != "i"]
    
  • 使用列表理解
  • 教程中或中的详细信息

    建议的修改:

    #Leer Txt - Read txt
    with open("Z:\\R\\Desktop\\BIFIDO\\easy.txt", "r") as document:
        contenido = document.read()
        print (contenido)
    
    #Genera alfabeto-Generate Alphabet
    alfa = [chr(i) for i in xrange(97, 123) if chr(i) != "i"]
    
    (请注意,此更改还包括列表中的一个条件-)

    而且:

    #Encripta fase1 - Get's coordinates of txt    
    encripta = [alfacor[e] for e in contenido]
    
  • 使用生成器
  • 首先,你可以从以下内容开始。编写列表理解时,如果知道一次只迭代列表中的一项,请将括号从
    []
    更改为
    ()
    。这真的很简单,但这是你能做的第一件事。另一个相关提示是,当您使用
    range(x)
    时,就像使用
    表示range(x)
    中的i一样,请使用
    xrange(x)
    xrange
    range
    的生成器版本

    更多信息请访问

    建议更改:

    #Make a new list from zipped to convert from tuple to list
    final_list = (list(elem) for elem in zipped)
    
  • 打印
  • 在本例中,使用您使用的打印是可以的,但请查看字符串格式

    更详细,更详细

    可能的变化:

    print "Tu palabra {}".format(encripta_f)
    
  • 您不需要初始化所有变量
  • 为变量指定一个全新的值时,无需初始化alfacor
    字典。不过,在以后使用该变量时,需要对其进行初始化

    因此,两者之间存在差异

    # no need for initialization
    alfacor = {}
    # because you assign a new value here to the variable `alfacor`
    alfacor = dict(zip(alfa,coordinates))
    
    这是:

    # you need to initialize this
    alfacor = {}
    # because you are working with the empty dictionary here
    alfacor["my_key"] = "my_value"
    

    除了使用理解和避免不必要的元组->列表->元组转换之外,减少中间变量的数量可能会稍微容易一些。我也会考虑把它变成一个函数,在一个字符串中传递,一个加密的字符串返回:

    from itertools import chain, product
    
    def bifid(data):
        # Leave coordinates as tuples and appropriate use of itertools.product
        coordinates = product(range(1, 6), repeat=2)
    
        # Using comprehensions and generators to construct the list/dicts vs loops
        # Leave alfa as a generator as it is only used once
        alfa = (chr(i) for i in range(97, 123) if chr(i) != 'i')
        alfacor = dict(zip(alfa, coordinates))
        inv_alfacor = {coordinate: letter for letter, coordinate in alfacor.iteritems()}
        encripta = (alfacor[e] for e in data)
    
        merged = list(chain(*encripta))
        final_list = zip(merged[:len(merged)//2], merged[len(merged)//2:])
    
        return "".join(inv_alfacor[e] for e in final_list if e in inv_alfacor)
    
    # Use with it closes automatically and handles exceptions correctly
    with open("Z:\\R\\Desktop\\BIFIDO\\easy.txt") as document:
        data = document.read()]
    
    print "Tu palabra: {}".format(bifid(data))
    
    输出:

    "helloworld" -> Tu palabra: kmcyobnalt
    

    这个问题看起来更像是一个主题。询问关于代码风格的意见在这里是离题的。谢谢你的提示,我不知道,在以后的帖子中会考虑到。你应该摆脱这个额外的开放statement@achampion谢谢,修复了。@Marek哇,非常感谢您的详细解释,这在不久的将来会非常有用。@etsous很高兴我能帮上忙。看看这个教程,它可能是我读过的最有用的Python材料。我对代码缩减印象深刻,非常感谢。