用字符串和数字对列表排序

2024-09-27 07:28:48 发布

您现在位置:Python中文网/ 问答频道 /正文

我需要帮助用python组织一个列表。 我需要的是: 我有一个这样的列表:[10,50,20,'STRING',5],我需要组织这个列表,不移动字符串,像这样:[5,'STRING'10,20,50]。你能这样做吗? 谢谢!你知道吗

我需要创建一个链表来检查两个字符串中是否有交集,我在'def Intersecao'处检查,输出需要排序,如果交集为空,我需要打印字符串'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)

Tags: noselfnonereturndefvalorappendlista
1条回答
网友
1楼 · 发布于 2024-09-27 07:28:48

对于第一个问题,如果只是列表,一种方法是(可能有更好的方法,尽管):

# 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

输出相同。你知道吗

相关问题 更多 >

    热门问题