Un utilisateur souhaite saisir des données comme ci-dessous et enregistrer N sous forme de liste d'entiers et B sous forme de liste de chaînes.
Contribution:
N=list(map(int, input())) B = list(map(str, input().split()))
Ensuite, je veux enregistrer ces deux listes comme ci-dessous:
N=[2,3,5] B=['hello world','how are you','what are you doing man']
J'ai commencé avec le code ci-dessous, mais je ne sais pas comment le mettre en boucle pour tous les enregistrer.
2 hello world 3 how are you 5 what are you doing man
3 Réponses :
Vous pouvez faire ce qui suit:
aux = [input() for _ in range(6)] N = list(map(int, aux[::2])) B = aux[1::2]
Ou, peut-être moins cryptique:
N, B = lists = [], [] for i in range(6): lists[i%2].append(input()) N = list(map(int, N))
Une approche est très simple et explicite. A while
boucle peut être utilisé pour garder les invites de roulement, jusqu'à ce qu'une commande exist (dans ce cas: x
) est donné.
Exemple:
N >>> [5, 15, 20] B >>> ['Hello.', 'How are you?', 'Very well, thank you.']
Instructions:
Enter an integer, then string (or [x] to exit): 5 Hello. Enter an integer, then string (or [x] to exit): 15 How are you? Enter an integer, then string (or [x] to exit): 20 Very well, thank you. Enter an integer, then string (or [x] to exit): x
Production:
N, B = [], [] while True: print('Enter an integer, then string (or [x] to exit):') n = input() if n != 'x': N.append(int(n)) B.append(input()) else: break
Que diriez-vous d'un bloc-notes python en temps réel:
[2, 3, 5] ['hello world', 'how are you', 'what are you doing man']
Exécutez simplement le code ci-dessus et tapez jusqu'à ce que vous appuyiez deux fois sur ENTRÉE sans autres caractères. Contribution:
2 hello world 3 how are you 5 what are you doing man
Production:
N = [] B = [] i = 0 while True: lst = B if i % 2 else N i += 1 text = input() lst.append(text) if lst: if not text and not lst[-1]: lst.pop() break N = list(map(int, N)) print(N) print(B)