Sto cercando una funzione o un programma breve che riceva una stringa (fino a 10 lettere) e la mischia.
grazie Arielshuffle string in python
32
A
risposta
42
C'è una funzione shuffle nel modulo casuale. Si noti che mescola sul posto in modo da avere prima di convertire la stringa a un elenco di caratteri, in ordine casuale, poi unirsi di nuovo il risultato.
import random
l = list(s)
random.shuffle(l)
result = ''.join(l)
66
>>> import random
>>> s="abcdef123"
>>> ''.join(random.sample(s,len(s)))
'1f2bde3ac'
-2
un take alternativo per mischiare una stringa:
# Python < 3
import random, array
def shuffle_text(text):
if isinstance(text, unicode):
temp= array.array('u', text)
converter= temp.tounicode
else:
temp= array.array('c', text)
converter= temp.tostring
random.shuffle(temp)
return converter()
ho aggiunto questa risposta solo per completezza amor; sul mio server di casa lento, è più veloce per stringhe di input di piccole dimensioni (ma la differenza è molto piccola), mentre è più lenta per stringhe più grandi.
Problemi correlati
- 1. Shuffle in Python
- 2. prestazioni dell'algoritmo python shuffle
- 3. String reverse in Python
- 4. Come "shuffle" un array?
- 5. Colonne shuffle
- 6. Pyspark: shuffle RDD
- 7. Pare bson string in python?
- 8. Parsing time string in Python
- 9. python shuffle tale che la posizione non si ripeterà mai
- 10. Algoritmi Lazy Shuffle
- 11. Shuffle array swift 3
- 12. String Affettare Python
- 13. Shuffle dataframe righe
- 14. Python Decimal to String
- 15. Python repeat string
- 16. python "string" module?
- 17. shuffle vs permute numpy
- 18. shuffle: influenza di tipo
- 19. Python regex string matching?
- 20. None vs Empty String in Python
- 21. Fuzzy String Ricerca con Whoosh in Python
- 22. ottenere string tra 2 caratteri in python
- 23. String diviso con gli indici in Python
- 24. Scala ListBuffer (o equivalente) shuffle
- 25. Spark - Shuffle Read Blocked Time
- 26. Lista Shuffle <T>
- 27. Python - Parse string, struttura nota
- 28. Parse Python String per unità
- 29. String regex due disallineamenti Python
- 30. Rimuovi Sub String usando Python
+1 per la "in-place". Quindi 'print random.shuffle (['a', 'b', 'c'])' restituirà 'None'. Dobbiamo usare 'L = [ 'a', 'b', 'c']' 'quindi random.shuffle (L)' e 'L' stampa invece. – Basj