我需要帮助在python中组织一个列表。我需要的是:我有一个这样的列表:[10,50,20,'STRING',5],我需要组织这个列表,不移动字符串,比如:[5,'STRING'10,20,50]。有可能这样做吗?谢谢!
我需要创建一个链接列表来检查是否有两个字符串中的交集,我在'def‘处检查,输出需要排序,如果交集是空的,我需要打印字符串'VAZIO’。
class No():
def __init__(self, valor = None, proximo = None):
self.valor = valor
self.proximo = proximo
def getValor(self):
return self.valor
def getProximo(self):
return self.proximo
def setProximo(self, novo_proximo):
self.proximo = novo_proximo
class lista():
def __init__(self, inicio = None):
self.inicio = inicio
def Inserir(self, valor):
novo_no = No(valor)
novo_no.setProximo(self.inicio)
self.inicio = novo_no
def Buscar(self, valor):
dados = self.inicio
while dados:
if dados.getValor() == valor:
return dados
else:
dados = dados.getProximo()
return None
def Intersecao (self, lista):
no = self.inicio
intersecao = []
while no != None:
if (not lista.Buscar(no.getValor())):
no = no.getProximo()
else:
if(no.getValor() == ''):
intersecao.append('VAZIO')
no = no.getProximo()
elif(no.getValor() in intersecao):
no = no.getProximo()
else:
intersecao.append(no.getValor())
no = no.getProximo()
return intersecao
def MostrarLista(self):
lista = []
dados = self.inicio
while dados:
lista.append(str(dados.getValor()))
dados = dados.getProximo()
print('->'.join(lista))
MyList = lista()
MySecondList = lista()
lista = []
lista2 = []
for i in range(40):
dado = input()
if i < 20:
lista.append(dado)
elif i >= 20:
lista2.append(dado)
for i in lista:
MyList.Inserir(i)
for i in lista2:
MySecondList.Inserir(i)
listaOrdenada = []
for elementos in sorted(MyList.Intersecao(MySecondList)):
print(elementos)发布于 2017-03-21 02:32:20
对于第一个问题,如果只列出清单,一种方法是(可能有更好的方法):
# original list
my_list = [10,50,20,'STRING',5]
# Creating temporary list with all numbers in sorted order and reverse
# reversed such that we use pop() which is efficient in time complexity
sorted_list = sorted([element for element in my_list if not isinstance(element, str)], reverse=True)
# new list to append accordingly
new_list = []
# for each element if it is string then in new list it has same position as in original list
# else if it was originally number then, we append the respective sorted number
for index, element in enumerate(my_list):
if isinstance(element, str):
new_list.append(element)
else:
new_list.append(sorted_list.pop())
new_list 输出:
[5, 10, 20, 'STRING', 50]或者,它可以通过清单理解来完成,而清单理解看起来更清晰:
# Using list comprehension
my_list = [10,50,20,'STRING',5]
sorted_list = sorted([element for element in my_list if not isinstance(element, str)], reverse=True)
new_list = [element if isinstance(element, str) else sorted_list.pop() for index, element in enumerate(my_list)]
new_list给出了同样的输出。
https://stackoverflow.com/questions/42917129
复制相似问题